Archived topic
Hide categories that have no posts within them
4 replies · Started by Matthew on May 22, 2019
Hi
I would like to hide the categories in the menu that have no posts within them.
I believe this is possible from what I have looked up using hide_empty, however from what I have found it depends on the theme is querying the categories.
Is there a simple way to have the categories hide in the menu if there are no posts within them?
Hi Matt,
I'm a newbie and not from GP support, but it seems I've asked the same question.. and David's answered. I'm sorry in advance if it is not the case and if I misunderstood your question xD
There are 2 possibilities depending if you want exclude Categories from Blog archive or from the Widget Categories only.
have a look there:
https://generatepress.com/forums/topic/hide-categories-into-widget-categories/#post-906756
or there https://generatepress.com/forums/topic/need-separate-page-for-blog-post-category/#post-643002
edit: this solution could also be suitable in some cases: https://wpshowposts.com/
Hey Sebastien
Cheers for the reply I did actually come across these, but I forgot to mention that this is specifically in the menu I am trying to do this.
I actually think I have managed to find a solution to this after a lot of Googling 😂, looks like I didn't need to know how the theme was querying the categories.
Used this code in case anyone else comes across this thread:
add_filter( 'wp_get_nav_menu_items', 'nav_remove_empty_category_menu_item', 10, 3 );
function nav_remove_empty_category_menu_item ( $items, $menu, $args ) {
global $wpdb;
$nopost = $wpdb->get_col( "SELECT term_taxonomy_id FROM $wpdb->term_taxonomy WHERE count = 0" );
foreach ( $items as $key => $item ) {
if ( ( 'taxonomy' == $item->type ) && ( in_array( $item->object_id, $nopost ) ) ) {
unset( $items[$key] );
}
}
return $items;
}
Thanks Sebastian and glad to hear you got it resolved Matt and thanks for sharing the solution.