Reputation: 55
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
Upvotes: 2
Views: 1484
Reputation: 254231
Try to use reset()
to get the first term as follows:
$term_names = wp_get_post_terms( $post->ID, 'product_cat' array('fields' => 'names') );
echo reset($term_names);
This will display the first term name.
And using end()
will display the last one:
$term_names = wp_get_post_terms( $post->ID, 'product_cat' array('fields' => 'names') );
echo end($term_names);
Upvotes: 2