2
$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

  • child_cats is missing $, so replace child_cats with $child_cats and see if it works then. – stealthyninja Jan 16 '18 at 10:00
  • Turn DEBUG on and you'll get interesting data. – Max Yudin Jan 16 '18 at 13:12
  • Nothing interesting when debug set to true. – Dev Jan 16 '18 at 13:54
-1

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.

| improve this answer | |
  • Close but the problem with this is it returns all categories. I only need it to return the parent category the post is assigned to. It half works. See edit 2. – Dev Jan 16 '18 at 14:16
  • Use the better wp_get_post_categories – yomisimie Jan 16 '18 at 14:23
-1

using this code

function rk_fix_tax_queries_on_archives( $query ) {
    // Only run this on the main query for the category archive
    if ( ! is_admin() && $query->is_category() && $query->is_main_query() ) {
        // What category is this
        $cat = $query->query_vars['category_name'];
        // Build the new query args
        $tax_query = array(
            array(
                'taxonomy'         => 'category',
                'field'            => 'slug',
                'terms'            => $cat,
                'include_children' => false,
            ),
        );
        // Set the new query args to $query->query_vars['tax_query']
        $query->set( 'tax_query', $tax_query );
        // Setting the query args is not enough, we have to create a new tax query object
        // and force feed it to the query
        $query->tax_query = new WP_Tax_Query( $tax_query );
    }
}
add_action( 'parse_tax_query', 'rk_fix_tax_queries_on_archives' );
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.