search

Home  >  Q&A  >  body text

Custom shortcode for child and grandchild product taxonomy terms not working as expected

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粉940538947P粉940538947251 days ago686

reply all(1)I'll reply

  • P粉141455512

    P粉1414555122024-03-21 09:49:17

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

    reply
    0
  • Cancelreply