I’ve done a bit of work on my wordpress blogs recently involving creating a new category which covers stuffs I’m interested in but maybe not-so-interesting for my blog’s regular readers and feed subscribers. I’ve managed to exclude the whole category from showing up in my blog’s homepage (index), feeds and the recent posts sidebar. Here’s how I did it.
No wordpress plugins needed
Although there are a few wordpress plugins floating around which promise to do the same, I’ve had no luck with them and prefer to do this manually instead. It’s easy!
Exclude Categories From Home & Feeds
1. Goto wp-admin > Appearance > Editor and there should be a file named functions.php
2.
function exclude_category($query) { if ( $query->is_feed || $query->is_home ) { $query->set('cat','-23,-34'); } return $query; } add_filter('pre_get_posts','exclude_category');
3. In the above example, 23 and 34 are the categories which I would like to exclude from the home (index) and feeds section. Note that the minus sign specifies that it’s an excluded directory.
Exclude Categories From Recent Posts Archives
Previously, I’ve used wp_get_archives to fetch the latest 10 posts and show it on the sidebar. But unfortunately, wp_get_archives doesn’t allow you to pass in arguments to specify what categories to include or exclude.
So one way to get around this was to create a function (I will call it get_archives_exclude_category), place it into functions.php (refer step 1 above), and call the function to populate a list of recent posts whenever it’s needed.
function get_archives_exclude_category() { $temp_query = $wp_query; query_posts("showposts=10&cat=-23"); while (have_posts()) { the_post(); ?> <li><a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to “<?php the_title(); ?>”"><?php the_title(); ?></a></li> <?php } return $wp_query = $temp_query; }
With that, I can then edit my sidebar/widget using
<?php get_archives_exclude_category() ?>
and get back 10 recent posts with posts from category 23 excluded.
Leave a Reply