terms - get parent and childs from hierarchcial taxonomy

admin2025-06-03  3

I have a hierarchical taxonomy and I want to show only children from 1 parent.

For example, the taxonomy looks like this:

- Events
-- Location
-- Date
- Region
-- State
-- StateCode

When I use my code, I get all child values...

$terms = get_terms( array(
    'taxonomy' => 'events_category',
    'hide_empty' => false,
) );

foreach ($terms as $term) {
    if ($term->parent != 0) { // avoid parent categories
        $options[] = array('label' => $term->name, 'value' => $term->term_id, 'id' => $term->term_id);
    }
}

Is it possible, that I can modify this lines to get only the children from Events for example?

I have a hierarchical taxonomy and I want to show only children from 1 parent.

For example, the taxonomy looks like this:

- Events
-- Location
-- Date
- Region
-- State
-- StateCode

When I use my code, I get all child values...

$terms = get_terms( array(
    'taxonomy' => 'events_category',
    'hide_empty' => false,
) );

foreach ($terms as $term) {
    if ($term->parent != 0) { // avoid parent categories
        $options[] = array('label' => $term->name, 'value' => $term->term_id, 'id' => $term->term_id);
    }
}

Is it possible, that I can modify this lines to get only the children from Events for example?

Share Improve this question edited Feb 19, 2019 at 10:18 Krzysiek Dróżdż 25.6k9 gold badges53 silver badges74 bronze badges asked Feb 19, 2019 at 9:57 LovinQuaQuaLovinQuaQua 833 silver badges19 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Yes, you can.

get_terms function takes $args as first param. And you can use the same args as with WP_Term_Query.

Two arguments that may interest you are:

  • child_of - (int) Term ID to retrieve child terms of. If multiple taxonomies are passed, $child_of is ignored. Default 0.
  • parent - (int|string) Parent term ID to retrieve direct-child terms of.

So if you want to get only the terms that are children of Event term, then you can use this code:

$terms = get_terms( array(
    'taxonomy' => 'events_category',
    'hide_empty' => false,
    'child_of' => <EVENTS_TERM_ID>,  // <-- you have to replace this with the term id of Events term.
) );

This way you don't need any ifs in printing code any more.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748891008a314579.html

最新回复(0)