I have a mystery with the categories from WooCommerce. For different products I have multiple categories. For example the product Nike Air Red I connect this product with two categories Brands->Nike and Shoes->Red Brands and Shoes are main categories and Nike and Red are subcategories.
On the product page I have the following code
$terms = wp_get_post_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
echo $term->name;
}
The output is NikeRed
Is there a way to get one category? Nike or Red?
I tried also
get_ancestors(get_queried_object_id(), 'product_cat')
But this array is empty
$terms = wp_get_post_terms( $post->ID, 'product_cat', array('parent' => '0') );
but this returns both categories Nike and Red. I want just one of these – Bert