Home > Net >  Get child of terms from WP_Term_Query
Get child of terms from WP_Term_Query

Time:06-09

I'm new to WordPress and like to get all the terms which are the children of term_id = 1,

Below is my code snippet of Term Query, and in the screenshot shows the category structure.

But what i got from the log, it will show all of terms. I tried 'parent' as well, but not work.

(Version WordPress 6.0)

$term_args = [
    'taxonomy'              => 'category',
    'hide_empty'            => 0,
    'hierarchical'          => 1,
    'child_of'              => 1
];

$terms = new \WP_Term_Query($term_args);
if (!is_admin()){
    var_dump($terms->get_terms());
}

enter image description here

CodePudding user response:

Use get_terms for that. Below code gets all child terms for a parent.

$args = array(
    'taxonomy'              => 'category',
    'hide_empty'            => 0,
    'hierarchical'          => 1,
    'child_of'              => 1
);

$taxonomies = get_terms( $args );
if ( !empty( $taxonomies ) || !is_wp_error( $taxonomies ) ) {
    var_dump($taxonomies);
}

It works on my end!

  • Related