Display 2 different custom taxonomy terms on single product page
-
Our WooCommerce products have two custom taxonomies: sizes and colors.
I’m trying to display the custom toxonomy terms for a product on its single product page. I’m using the woocommerce_single_product_summary action hook. I can’t get both taxonomies to display at the same time.
Here’s my code so far:
<?php /** * display a woocommerce product's custom taxonomy terms on single product pages */ function display_single_product_sizes_after_summary() { global $post; $size_terms = get_the_terms( $post->ID , array( 'sizes') ); // begin creating html markup $size_markup = ''; if(!empty($size_terms)) { $size_markup .= "<p>Similar size shades: "; } // init counter $is = 1; foreach ( $size_terms as $size_term ) { $size_markup .= '<a href="/shades/size/' . $size_term->slug . '">' . $size_term->name . '</a>'; // Add comma (except after the last item) $size_markup .= ($is < count($size_terms))? ", " : ""; // Increment counter $is++; //finish the markup if(!empty($size_terms)) { $size_markup .= "</p>"; } } echo $size_markup; }; function display_single_product_colors_after_summary() { global $post; $color_terms = get_the_terms( $post->ID , array( 'colors') ); // begin creating html markup $color_markup = ''; if(!empty($color_terms)) { $color_markup .= "<p>Similar color shades: "; } // init counter $ic = 1; foreach ( $color_terms as $color_term ) { $color_markup .= '<a href="/shades/color/' . $color_term->slug . '">' . $color_term->name . '</a>'; // Add comma (except after the last item) $color_markup .= ($ic < count($color_terms))? ", " : ""; // Increment counter $ic++; //finish the markup if(!empty($color_terms)) { $color_markup .= "</p>"; } } echo $color_markup; }; function display_single_product_terms_after_summary() { display_single_product_sizes_after_summary(); display_single_product_colors_after_summary(); }; add_action( 'woocommerce_single_product_summary', 'display_single_product_terms_after_summary', 101, 0 ); ?>
This outputs the following:
Similar size shades: Small
Similar color shades:
If I reverse the order of the two sub-functions in display_single_product_traits_after_summary the output changes to:
Similar color shades: Blue
Similar size shades:
I’ve tried to use a reset at the end of each subfunction. I’ve tried:
echo $size_markup; wp_reset_postdata();
and:
echo $color_markup; wp_reset_postdata();
This makes no difference.
I’ve also tried:
echo $size_markup; rewind_posts();
and:
echo $color_markup; rewind_posts();
This breaks the page altogether.
What is my mistake here, and how can I get the terms from both taxonomies to display?
- The topic ‘Display 2 different custom taxonomy terms on single product page’ is closed to new replies.