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?
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 if
s in printing code any more.