Search code examples
phpwoocommerceshortcode

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


I'm using 2 shortcodes [brandname] and [productname] to display the child and grandchild taxonomy terms on a product Single template.

Example 1: Smartphone > Apple > iPhone 14
Example 2: Tablet > Apple > iPad Pro 12.9 inch (5th gen)

Example 1 shortcodes works fine Example 2 shortcodes don't, both shortcodes display the grandchild taxonomy term.

The 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 to select only the grandchild term for the product, but that didn't do anything.


Solution

  • I managed to get it working! This is the working code for the [brandname] shortcodes:

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