Dimitris
Dimitris

Reputation: 35

How to hide wordpress empty SUB-CATEGORIS ONLY?

I am using this code to hide the empty categories, and it works.

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;
}

But I want it to work for subcategories only... not the parent category. So right now it hides some parent categories and I don't want that. I want to hide only the empty subcategories.

How can I do that?

Upvotes: 2

Views: 97

Answers (1)

Xhynk
Xhynk

Reputation: 13840

You don't need a recursive function at all. The term_taxonomy table has another column called parent, which is set to 0 if it's a top level item, and will be the parent's ID if it's a child at any level. Simply add

AND parent != 0

to your query, and that should take care of it. (That said, I feel like pulling the terms and looping through the items for a match to unset is a bit overkill, but without knowing more it's tough to recommend a better solution, and this isn't a bad way to go about it - one of those "hammers to kill a fly" things.)

It may be (quite) a bit pedantic, but I also prefer writing SQL statements outside of the helper functions to make it easier to see at a glance what needs to be run through ::prepare, and deal with longer queries easier

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;

    $sql = "
        SELECT term_taxonomy_id
        FROM   $wpdb->term_taxonomy
        WHERE  count = 0
        AND    parent != 0
    ";

    $no_posts = $wpdb->get_col( $sql );

    foreach( $items as $key => $item ){
        if( 'taxonomy' == $item->type && in_array($item->object_id, $no_posts) ){
            unset( $items[$key] );
        }
    }

    return $items;
}

Upvotes: 1

Related Questions