Skip to content
Advertisement

Get only one product category term for a WooCommerce product

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

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement