How to exclude categories from recent posts, recent comments & category widgets?

I use the bellow function (thanks to @helgatheviking!) to exclude categories from the wordpress loop. It works very well – posts of selected categories are excluded from the loop on the main blog listing page, from category listing pages and from archives, but not from Recent Posts and not from Recent Comments in sidebar. How can be extended the action of this code also on them?

add_action('pre_get_posts', 'wpa_31553' );

function wpa_31553( $wp_query ) {

    //$wp_query is passed by reference.  we don't need to return anything. whatever changes made inside this function will automatically effect the global variable

    $excluded = array(272);  //made it an array in case you need to exclude more than one

    // only exclude on the front end
    if( !is_admin() ) {
        set_query_var('category__not_in', $excluded);
        //which is merely the more elegant way to write:
        //$wp_query->set('category__not_in', $excluded);
    }
}

UPDATE:
A small clarification, the excluded categories have not disappeared also from the Categories widget. Just disappeared all posts from these categories when I open them with a mouse click. I would like that they disappear also from the Categories widget.

4 Answers
4

The original author isn’t quite right in saying “which is merely the more elegant way to write”.

set_query_var() will always override the main query, whereas if you actually use:

$wp_query->set( 'category__not_in', $excluded );

… it will work for any instance of query_posts(), such as the recent posts widget.

Leave a Comment