Rahul vats
Rahul vats

Reputation: 31

How to get all parents/children categories of a custom taxonomy in WordPress

I’m working on a custom WordPress theme and I want to show all the taxonomies list

So, for example, if I want this structure:

  1. Parent Category 1

    • Child Category 1
    • Child Category 2
    • Child Category 3

      1.1 - Grand Child Category 1

  2. Parent Category 2

    • Child Category 4
    • Child Category 5

      2.1. - Grand Child Category 2

can you guys please help me to solve this puzzle

Upvotes: 1

Views: 3968

Answers (2)

Mahfuzul Hasan
Mahfuzul Hasan

Reputation: 172

Try this function: replace "taxonomy_name" with your taxonomy.

wp_list_categories( array('taxonomy' => 'taxonomy_name', 'title_li' => "") );

Output:

Output look like this

Note: I have used WP 4.9.8

Upvotes: 1

Yuxel Yuseinov
Yuxel Yuseinov

Reputation: 340

To create this structure, maybe going with a helper array is the solution. This is not a 100% solution it will just give you start up and you can go from here since figuring it out all alone will be more helpful.

$all_terms = array();
$taxonomy = 'category';
$parent_args = [
    'taxonomy'     => $taxonomy,
    'parent'        => 0,
    'hide_empty'    => false
];
$parent_terms = get_terms( $parent_args );

foreach ( $parent_terms as $parent_term ) {
   $all_terms[ $parent_term->term_id ] = get_all_term_children( $parent_term, $taxonomy );
}

function get_all_term_children( $term, $taxonomy ){
    if ( is_wp_error( get_term_children( $term->term_id, $taxonomy ) ) ) {
        return;
    }

    return get_term_children( $term->term_id, $taxonomy );
}

Upvotes: 2

Related Questions