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.
I successfully made it work! Here is the working code for the [brandname] shortcode: