получите условия - только высший уровень


Этот код хорошо работает:

$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 />";
    }
}

Он генерирует:

  • Термин 1 (первый уровень - родительский)
  • Термин 2 (второй уровень - дочерний)

Я хотел бы получить только термины первого уровня. Как его изменить?

Author: reti, 2020-05-15

1 answers

Просто проведите быстрый тест, и, похоже, оба метода работают хорошо.

// @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 />";
      }
    }
}
 2
Author: simongcc, 2020-05-15 14:10:25