1

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.com/');
        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?

1
  • 1
    Untested guess: put if ($term->parent) continue; at the top of the for loop.
    – Rup
    May 15 '20 at 13:12
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.com/');
        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.com/');
        echo "<a href='$link'>$name</a><br />";
      }
    }
}
1
  • Yes, both methods working well. Thanks a lot! I'm very grateful for your help.
    – reti
    May 15 '20 at 16:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.