Reputation: 71
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?
Upvotes: 0
Views: 6552
Reputation: 1481
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.
Upvotes: 2