Exclude Child Categories Using wp_list_categories

$category = get_category( get_query_var( 'cat' ) );

$child_cats = (array) get_term_children( $category , 'category' );

wp_list_categories( array(
        'exclude'  => $child_cats
    ) );

Is it possible to exclude all child categories?

Update : I tried this also but it doesn’t work.

$categories = get_categories( array(
        'childless'  => true,
    ) );

    $child_cats = (array) get_term_children( $categories, 'category' );

    $cats = wp_list_categories( array(
        'exclude' => $child_cats
    ) );

Edit 2 : I preferably would like this to work with get_the_category_list

2 Answers
2

Instead of excluding child categories, try to get only categories that have no parents (0)

    $cats = wp_list_categories( array(
        'parent' => 0
    ) );

That should work with no issues.

EDIT: get_the_category_list() does not support advanced arguments. Your best bet is wp_get_post_categories($post_id, array(‘parent=>0’)). That will return an array of objects, you have to do the HTML yourself with a foreach loop.

Leave a Comment