[Resolved] Hide categories that have no posts within them

Home Forums Support Hide categories that have no posts within them

Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #907482
    Matthew

    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?

    #907516
    Sebastien

    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/

    #907536
    Matthew

    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.

    #907543
    Matthew

    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;
    }
    
    #907622
    David
    Staff
    Customer Support

    Thanks Sebastian and glad to hear you got it resolved Matt and thanks for sharing the solution.

Viewing 5 posts - 1 through 5 (of 5 total)
  • You must be logged in to reply to this topic.