Show only 1 term of a current posts taxonomy

I’ve been using this code to display the taxonomy term of the current post.

$terms = wp_get_post_terms($post->ID, 'custom_cat');
foreach($terms as $term){
    print_r($term->name);
    unset($term);
}

Which is fine, except now I have some posts with 2 or more terms associated with them and it’s throwing off my layout.

Read More

Is there a way that I can show only 1 of the terms?

Related posts

1 comment

  1. This is more PHP than WordPress, but wp_get_post_terms returns a numerically indexed array, so all you need is basic PHP array syntax to grab the first item.

    $terms = wp_get_post_terms($post->ID, 'custom_cat');
    
    print_r($terms[0]->name);
    

    You don’t specify which item you want. This will get you last item:

    $terms = array_pop($terms);
    print_r($terms);
    

Comments are closed.