Excluding categories from Worpdress home page

I wanted to exclude a category from my home page, as to not clutter the feed(?) with every single post I do. I was contemplating between making an inclusion or exclusion type of filtering, but I couldn’t really find the former, so exclusion it was.

Having googled a little, I made a choice between two methods

  • Plugin – https://wordpress.org/plugins/ultimate-category-excluder
  • Editing the theme (functions.php)

In the end I chose editing the theme. I know it’s going to be error prone and one day the code modification will break because the methods use will change names or whatever. But it’s either that or making sure the plugin is maintained. Either way, it will need monitoring and coming up with ways to address each respective situation.

Here’s a summary of what I did

  1. Log in to WP admin backend
  2. Determine the id of a category
    1. Navigate to Posts -> Categories
    2. Hover over the category you want to exclude, note down the number after “tag_ID=”
  3. Edit the functions.php-file
    1. Navigate to Appearance -> Theme File Editor, and in the file list to the right, click “Theme Functions (functions.php)”
    2. In the editor, scroll to the bottom, add a few empty lines to the bottom and paste the following snippet
function exclude_category_home( $query ) {
    if ( $query->is_home ) {
        $query->set( 'cat', '-tag_ID' );
    }
    return $query;
}
 
add_filter( 'pre_get_posts', 'exclude_category_home' );
  1. Replace “tag_ID” with the id you gathered during step 2. If you for example noted down the category id as being “4”, then the code would look like set( 'cat', '-4' ). You can add multiple categories like so `set( 'cat', '-4, -32, -12' )
  2. Save the changes
  3. Load your blog home page and take note if the posts containing your excluded categories are excluded.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.