Skip to content

Instantly share code, notes, and snippets.

@morgyface
Created May 26, 2022 10:28
Show Gist options
  • Save morgyface/9a2d75f1a4992fd6f32f5e25b4ca56d0 to your computer and use it in GitHub Desktop.
Save morgyface/9a2d75f1a4992fd6f32f5e25b4ca56d0 to your computer and use it in GitHub Desktop.
WordpPress | Get the first term of a taxonomy assigned to a post
<?php
$taxonomy = 'taxonomy';
if( has_term( '', $taxonomy ) ) {
$terms = get_the_terms( $post->ID, $taxonomy );
$term = array_shift( $terms );
$term_link = get_term_link( $term->term_id );
$term_name = $term->name;
}
?>
@morgyface
Copy link
Author

morgyface commented May 26, 2022

First term from the taxonomy terms assigned to a post.

Note this is different than get_term which simply, well, gets the term, this gets the terms assigned to the post using get_the_terms.

There are different ways to get the first element from an array, here we use the array_shift function. Also see array_pop which gets the last element.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment