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

customization - How to show parent taxonomy using get_the_terms?

programmeradmin2浏览0评论

I have registered one custom taxonomy. I am using this code to show this taxonomy on single.php.

But it shows parent and child terms as well.

function showorganisation()
{
    $terms = get_the_terms($post->ID, 'organization');
    foreach ($terms as $term) {
        $term_link = get_term_link($term, 'organization');
        if (is_wp_error($term_link))
            continue;
        echo '<a href="' . $term_link . '">' . $term->name . '</a>';
    }
}

How can I make it show parent terms only?

I have registered one custom taxonomy. I am using this code to show this taxonomy on single.php.

But it shows parent and child terms as well.

function showorganisation()
{
    $terms = get_the_terms($post->ID, 'organization');
    foreach ($terms as $term) {
        $term_link = get_term_link($term, 'organization');
        if (is_wp_error($term_link))
            continue;
        echo '<a href="' . $term_link . '">' . $term->name . '</a>';
    }
}

How can I make it show parent terms only?

Share Improve this question edited Mar 4, 2022 at 19:34 Fabrizio Mele 6875 silver badges16 bronze badges asked Mar 2, 2022 at 4:04 Prabhat JaniPrabhat Jani 11 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

get_the_terms() gives you an array of WP_Term objects. The object has parent (int) property, which tells you, if the term is a child and has a parent term or not.

This means that in your loop you can skip child terms with a simple if statement.

foreach ($terms as $term) {

  // Is it a child term?
  if ( $term->parent ) {
    continue;
  }

  // code...

}
发布评论

评论列表(0)

  1. 暂无评论