WordPress category widget only show categories with children

I’m trying to modify the inbuilt WordPress category widget to only show categories if they have children.

I was using this code:

function exclude_widget_subcategories($args){
$all_categories = get_all_category_ids();

$exclude_categories = array();

foreach($all_categories as $category_id){
$category = get_category($category_id);

if($category->parent!=0){
$exclude_categories[] = $category_id;
}
}
$exclude = implode(“,”,$exclude_categories); // The IDs of the excluding categories
$args[“exclude”] = $exclude;
return $args;
}
add_filter(“widget_categories_args”,”exclude_widget_subcategories”);

Which works in that it only shows top-level categories, however my client has various child-categories which also have children themselves and she wants these to show up in the category widget.

Is there a way I can modify this code so that instead of excluding categories which aren’t Parent categories it instead excludes categories that don’t have children?

Read more here:: WordPress category widget only show categories with children

Leave a Reply

Your email address will not be published. Required fields are marked *