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.
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:… it will work for any instance of
query_posts()
, such as the recent posts widget.Per @TheDeadMedic, I have adjusted my code. Hopefully it will now work on all non-admin queries.
This is what i would use to exclude categories from the categories widget
There are NO filters to exclude categories from the recent posts or recent comments widgets. You could rebuild the widget using this solution as a guide http://wordpress.org/support/topic/recent-posts-widget-with-category-exclude
I excluded my selected categories
from everywhere with the Advanced Category Excluder (ACE) plugin, except from Categories widget – here helped the @Brad Dalton code. ACE has an own Recent Comments widget that hides excluded categories, but here was a minor problem on 404 page, where this widget continues to show excluded categories that have comments, soI redirected it (the 404 page) to the home page of my site with the 404 to Start plugin.Thank you all for your help!
UPDATE
The Advanced Category Excluder plugin doesn’t have an option to select for which user roles are excluded specific categories, so I disabled it and also disabled the Recent Comments widget, for which I cannot exclude, for now, the needed categories. In conclusion, the only solution was the @helgatheviking and @Brad Dalton functions.