questions

Get only one product category term for a WooCommerce product

Rate this post

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

 

✔️Solution:

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);

Leave a Reply

Your email address will not be published.

Back to top button