I have a custom hierarchical taxonomy ('location') that looks like:


I have a post where only "Roppongi" is selected and I want to display as text only the top level parent term of the taxonomy (Tokyo) without any category link.

<?php $myterms = get_terms( array( 'taxonomy' => 'location', 'parent' => 0 ) );?>

The above code gives me...

Array ( [0] => WP_Term Object ( [term_id] => 11 [name] => Tokyo [slug] => tokyo [term_group] => 0 [term_taxonomy_id] => 11 [taxonomy] => location [description] => [parent] => 0 [count] => 0 [filter] => raw ) )

... as an output if I use...

<?php print_r($myterms);?>

... to display the result at the front-end. How do I display only the [name] value in the array? I tried the below code but get an error.

<?php echo $myterms[0]['name'];?>

2 Answers 2


It is an object, and you can use the following notation:

<?php echo $myterms[0]->name; ?>
  • Thank you for the help! This works for my example, but I other prefectures listed in my taxonomy and so it's shows 'Aichi' not Tokyo... how do I specify that it has to be the [name] from that term ID?
    – Gecko Boy
    Commented Jan 13, 2018 at 9:44

Try the following code. You will need post ID and the taxonomy name:

function wpse_290965_top_level_tax_name( $post_id, $tax )
    $terms = wp_get_post_terms( $post->ID, $tax );

    $anc = get_ancestors( $terms[0]->term_id, $tax );
    $parent = array_values( array_slice( $anc, -1 ) )[0];

    $term = get_term_by( 'id', $parent, $tax );
    return $term->name;

Now call it like: <?php echo wpse_290965_top_level_tax_name( 234, 'location' ); ?>

Here 234 is an example of post ID.

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.