With the following function you can get the first term of a post by the post’s id. The function requires 3 parameters:
$post_id
The id of the post to retrieve the term from.
$taxonomy
The taxonomy to retrieve terms from.
$output
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
Great blog you have got here.. It’s hard to find quality writing like yours nowadays.
I seriously appreciate individuals like you! Take care!!
Thank you so much! Glad I could help 🙂