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

佐手、 提交于 2020-12-14 23:24:05

问题


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


回答1:


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 );
}



回答2:


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

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

Output:

Note: I have used WP 4.9.8



来源:https://stackoverflow.com/questions/52738580/how-to-get-all-parents-children-categories-of-a-custom-taxonomy-in-wordpress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!