I have to get and show only one category name from a product. I have almost read everything and tried everything.

$term =  get_the_terms( $post->ID, 'product_cat' );
foreach ($term as $t) {
   $parentId = $t->all;
   if($parentId == 0){
     echo $t->name;
     $term = get_terms( 'product_cat', array('include' => array($parentId)) );


It shows one long string with all the category names. How should I get only one category and show its name.

1 Answer 1


Before I begin, just one note, there is no property called $all in get_the_terms. Here are the available fields which you can use

stdClass Object
    [term_id] =>
    [name] =>
    [slug] =>
    [term_group] => 
    [term_order] => 
    [term_taxonomy_id] =>
    [taxonomy] =>
    [description] => 
    [parent] =>
    [count] =>
    [object_id] =>

I'm not very sure what you want to achieve looking at your code, but if you need only one term from the returned array, you can do something like this: (NOTE: get_the_terms returns a WP_ERROR object on invalid taxonomy, so you want to check that, also check whether or not you have terms retrieved)

$terms =  get_the_terms( $post->ID, 'product_cat' );
if ( $terms && ! is_wp_error( $terms ) ) {
    echo $terms[0]->name;

$terms[0] will return the first term in the returned array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.