Get first term by post id

With the following function you can get the first term of a post by the post’s id. The function requires 3 parameters:

The id of the post to retrieve the term from.

The taxonomy to retrieve terms from.

What you want to return from the term. (term_id, name, slug, description etc.).

// Get first term by post id
function get_first_term_by_id( $post_id, $taxonomy, $output = 'term_id' ) {
   if ( isset( $post_id ) && isset( $taxonomy ) ) {
      $terms = get_the_terms( $post_id, $taxonomy );
      if ( ! empty( $terms ) ){
         $term = array_shift( $terms );
      return $term->$output;

2 Responses

  1. Great blog you have got here.. It’s hard to find quality writing like yours nowadays.

    I seriously appreciate individuals like you! Take care!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Robbert Vermeulen

Need help from a WordPress expert?

I would love to hear about your project and how I can help you achieve your goals