Benutzerdefinierter Shortcode für Produkttaxonomiebegriffe für Kinder und Enkel funktioniert nicht wie erwartet
P粉940538947
P粉940538947 2024-03-20 11:59:26
0
1
606

Ich habe zwei Shortcodes [Markenname] und [Produktname] verwendet, um Unterkategoriebegriffe und Enkelkategoriebegriffe in der Produkteinzelvorlage anzuzeigen.

Beispiel 1: Smartphone > iPhone 14

Beispiel 2: Tablets > iPad Pro 12,9 Zoll (5. Generation)

Beispiel 1 Shortcode funktioniert großartig Beispiel 2 Shortcode Keiner, beide Shortcodes zeigen den Enkelklassifizierungsbegriff an.

Code:

/**
 * Brandname for Product Single Page shortcode
 */

function child_category_shortcode($atts) {
  global $post;
  
  $product_terms = get_the_terms($post->ID, 'product_cat');
  
  if (!empty($product_terms)) {
    foreach ($product_terms as $term) {
      if ($term->parent != 0) {
        return $term->name;
      }
    }
  }
}

add_shortcode('brandname', 'child_category_shortcode');

/**
 * Productname for Product Single Page shortcode
 */

function grandchild_category_shortcode($atts) {
  global $post;
  
  $product_terms = get_the_terms($post->ID, 'product_cat');
  
  if (!empty($product_terms)) {
    foreach ($product_terms as $term) {
      $parent_id = $term->parent;
      if ($parent_id != 0) {
        $parent_term = get_term($parent_id, 'product_cat');
        $grandparent_id = $parent_term->parent;
        if ($grandparent_id != 0) {
          return $term->name;
        }
      }
    }
  }
}
add_shortcode('productname', 'grandchild_category_shortcode');

Ich habe versucht, nur das Enkelkind des Produkts auszuwählen, aber das hat nichts gebracht.

P粉940538947
P粉940538947

Antworte allen(1)
P粉141455512

我成功让它工作了!这是 [brandname] 短代码的工作代码:

function child_category_shortcode($atts) {
global $post;

$product_terms = get_the_terms($post->ID, 'product_cat');

if (!empty($product_terms)) {
    $child_terms = array();
    foreach ($product_terms as $term) {
        if ($term->parent != 0) {
            $parent = get_term($term->parent, 'product_cat');
            if ($parent->parent == 0) {
                array_push($child_terms, $term->name);
            }
        }
    }
    return implode(', ', $child_terms);
}
}
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!