仅获取条款顶级

时间:2020-05-15 作者:reti

此代码运行良好:

$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.com/\');
        echo "<a href=\'$link\'>$name</a><br />";
    }
}
它生成:

Term1(第一级-父级)

  • Term2(第二级-子级)
    • 我只想获得第一级术语。如何修改?

    1 个回复
    最合适的回答,由SO网友:simongcc 整理而成

    快速测试一下,两种方法似乎都很有效。

    // @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.com/\');
            echo "<a href=\'$link\'>$name</a><br />";
        }
    }
    

    $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.com/\');
            echo "<a href=\'$link\'>$name</a><br />";
          }
        }
    }