简体   繁体   中英

Woocommerce single product categories

On my woocommerce webshop the single product displays all categories it belongs to by using the following code:

    <?php
        $size = sizeof( get_the_terms( $post->ID, 'product_cat' ) );
        echo $product->get_categories( ', ', '<span class="posted_in">' . _n( '', '', $size, 'woocommerce' ) . ' ', '</span>' );
    ?>

Now I only want to display the top parent category and not the children the product belongs to.

I have tried a lot but nothing seems to work. Does anyone have a solutions for this?

try this

$term =  get_the_terms( $post->ID, 'product_cat' );
foreach ($term as $t) {
   $parentId = $t->parent;
   if($parentId == 0){
     echo $t->slug;
   }else{
     $term = get_terms( 'product_cat', array('include' => array($parentId)) );
   }
}

Let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM