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

php - get_the_terms - only top level

programmeradmin2浏览0评论

This code works good:

$terms = get_the_terms(get_the_ID(), 'my_taxonomy');
if (!is_wp_error($terms) && !empty($terms)) {
    foreach ($terms as $term) {
        $name = $term->name;
        $link = add_query_arg('fwp_typ', FWP()->helper->safe_value($term->slug), '/');
        echo "<a href='$link'>$name</a><br />";
    }
}

It generates:

  • Term1 (first level - parent)
  • Term2 (second level - child)

I would like to get only the first level terms. How to modify it?

This code works good:

$terms = get_the_terms(get_the_ID(), 'my_taxonomy');
if (!is_wp_error($terms) && !empty($terms)) {
    foreach ($terms as $term) {
        $name = $term->name;
        $link = add_query_arg('fwp_typ', FWP()->helper->safe_value($term->slug), 'https://www.freuciv/');
        echo "<a href='$link'>$name</a><br />";
    }
}

It generates:

  • Term1 (first level - parent)
  • Term2 (second level - child)

I would like to get only the first level terms. How to modify it?

Share Improve this question asked May 15, 2020 at 12:46 retireti 276 bronze badges 1
  • 1 Untested guess: put if ($term->parent) continue; at the top of the for loop. – Rup Commented May 15, 2020 at 13:12
Add a comment  | 

1 Answer 1

Reset to default 2

Just have a quick test and seems both methods working well.

// @Rup's method
$terms = get_the_terms(get_the_ID(), 'my_taxonomy');
if (!is_wp_error($terms) && !empty($terms)) {
    foreach ($terms as $term) {
      // skip if parent > 0
      if( $term->parent )
            continue;

        $name = $term->name;
        $link = add_query_arg('fwp_typ', FWP()->helper->safe_value($term->slug), 'https://www.freuciv/');
        echo "<a href='$link'>$name</a><br />";
    }
}

or

$terms = get_the_terms(get_the_ID(), 'my_taxonomy');
if (!is_wp_error($terms) && !empty($terms)) {
    foreach ($terms as $term) {
      // only do if parent is 0 (top most)
      if( $term->parent == 0 ) {
        $name = $term->name;
        $link = add_query_arg('fwp_typ', FWP()->helper->safe_value($term->slug), 'https://www.freuciv/');
        echo "<a href='$link'>$name</a><br />";
      }
    }
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论