I am trying to get the name for a custom taxonomy assigned to the current post and in my template I have:
$countries = get_terms( 'country', array('hide_empty' => false,));
$fcountry = $countries[0]->slug;
However this returns the first item in the $countries
array, instead of the term that is assigned to the current post.
I am trying to get the name for a custom taxonomy assigned to the current post and in my template I have:
$countries = get_terms( 'country', array('hide_empty' => false,));
$fcountry = $countries[0]->slug;
However this returns the first item in the $countries
array, instead of the term that is assigned to the current post.
1 Answer
Reset to default 1You should no longer use the legacy function parameter format. Instead, as the documentation says, use the get_terms( $args )
format:
Since 4.5.0, taxonomies should be passed via the ‘taxonomy’ argument in the
$args
array:$terms = get_terms( array( 'taxonomy' => 'post_tag', 'hide_empty' => false, ) );
And as for getting only the terms assigned to the current or a specific post, you can either use the object_ids
parameter with get_terms()
, or simply use get_the_terms()
.
So for examples:
$post_id = get_the_ID();
$countries = get_terms( array(
'taxonomy' => 'country',
'object_ids' => $post_id, // set the object_ids
) );
// Or just use get_the_terms():
$countries = get_the_terms( $post_id, 'country' );