Custom shortcode for child and grandchild product taxonomy terms not working as expected
P粉940538947
P粉940538947 2024-03-20 11:59:26
0
1
679

I use 2 shortcodes [Brand Name] and [Product Name] to display subcategory terms and grandchild category terms on the product single template.

Example 1: Smartphone > Apple > iPhone 14

Example 2: Tablets > Apple > iPad Pro 12.9-inch (5th generation)

Example 1 shortcode works well Example 2 Shortcode None, both shortcodes display the grandchild taxonomy term.

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');

I tried selecting only the grandchild of the product, but that didn't do anything.

P粉940538947
P粉940538947

reply all(1)
P粉141455512

I successfully made it work! Here is the working code for the [brandname] shortcode:

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);
}
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template