Site logo

[Resolved] Woocommerce / Display all Category Names for one Product

Home Forums Support [Resolved] Woocommerce / Display all Category Names for one Product

Home Forums Support Woocommerce / Display all Category Names for one Product

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #2427251
    Magnus

    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

    #2427555
    David
    Staff
    Customer Support

    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;
        }
    }
    ?>
    #2427756
    Magnus

    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);
    	}
    ?>
    
    #2428648
    David
    Staff
    Customer Support

    Glad to be of help and thanks for sharing your final version 🙂

Viewing 4 posts - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.