最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Get taxonomy name for the current post

programmeradmin2浏览0评论

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.

Share Improve this question asked Nov 23, 2020 at 19:40 JoaMikaJoaMika 6986 gold badges27 silver badges58 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

You 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' );
发布评论

评论列表(0)

  1. 暂无评论