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 Answer
Reset to default 2Just 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 />";
}
}
}
if ($term->parent) continue;
at the top of the for loop. – Rup Commented May 15, 2020 at 13:12