I need to show all associated product categories within the single product title. For example, selling a split-release record, which has two different artists categories associated.
Per this answer, the below code will display a single product category term within the product title.
function category_single_product(){
$terms = get_the_terms( get_the_ID(), 'product_cat' );
foreach ($terms as $term) ?>
<b><span itemprop="name" class="product_category_title"><span><?php echo $term->name; ?></span></span></b>
<?php }
add_action( 'woocommerce_before_shop_loop_item_title', 'category_single_product', 25 );
But it's not showing all associated product categories within the single product title. How can I display the multiple category terms?
To display all product categories associated to a product (at the end of the product title), try the following:
add_action( 'woocommerce_shop_loop_item_title', 'category_single_product', 20 );
function category_single_product(){
// Get product category terms for the current product
$terms = get_the_terms( get_the_ID(), 'product_cat' );
// Check if there are product categories assigned to the product
if ( $terms && ! is_wp_error( $terms ) ) {
// Get only an array of term names
$term_names = array_column( $terms, 'name' );
// Output the comma separated string of term names
printf('<b><span itemprop="name" class="product_category_title"><span>%s</span></span></b>', implode(', ', $term_names) );
}
}
It should work