Archived topic
Woocommerce / Display all Category Names for one Product
3 replies · Started by Magnus on November 22, 2022
Viewing posts 1–4 of 4
Hello,
I use this code
<?php
$terms = get_the_terms( get_the_ID(), 'product_cat' );
if ( $terms && ! is_wp_error( $terms ) ) :
if ( ! empty( $terms ) ) {
echo $terms[0]->name;
}?>
<?php endif;?>
to show the category of a product. But it only shows one category of each product. But some products have more than one category. How must the code be modified to show all selected categories of each product?
Thank you, Magnus
Hi there,
you can try:
<?php
$terms = get_the_terms( get_the_ID(), 'product_cat' );
if ( $terms && ! is_wp_error( $terms ) ) {
foreach ($terms as $term) {
echo $term->name;
}
}
?>
Hi David,
works perfect :-) If seperator needed here is the code for this
<?php
$terms = get_the_terms( get_the_ID(), 'product_cat' );
if ( $terms && ! is_wp_error( $terms ) ) {
$output = array();
foreach ($terms as $term) {
$output[] = $term->name;
unset($term);
}
echo implode(" | ", $output);
}
?>
Glad to be of help and thanks for sharing your final version :)
This archived topic is closed to new replies.