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;

I'm Robbert Vermeulen. I document everything I learn and help thousands of people with coding WordPress. My site has no ads or sponsors. If you enjoy my content, please consider supporting what I do.


  • Robbert Vermeulen

    August 8, 2021 at 11:03 am

    Thank you so much! Glad I could help :)

  • Ferdinand

    August 8, 2021 at 12:40 am

    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

Feel free to ask questions or make comments.