Prevent Posts in a Category From Displaying in WordPress’ RSS Feed

By  on  

I recently posted a snippet which prevented posts in a given category from displaying in WordPress' main loop.  I even went on to create my first WordPress plugin to accomplish the task via the WordPress control panel.  The one task those snippets doesn't complete is preventing posts from going into RSS feeds.  Here's how you can prevent posts in a category from displaying in the RSS feed!

The PHP

The category check is done the same way the loop check was done:

function postsFilter($query) {
    // Prevent from RSS feed
    if($query->is_feed()) {
    	// No posts in category #11 may go into the feed
    	$query->set('cat', '-11');
    }
}
add_action('pre_get_posts', 'postsFilter');

A pre_get_posts filter is added to check for the is_feed() return value.  If the value is true, we add the condition to remove the category form the final query.  I have added this functionality to the WordPress plugin as well!

Recent Features

Incredible Demos

  • By
    Elegant Overflow with CSS Ellipsis

    Overflow with text is always a big issue, especially in a programmatic environment. There's always only so much space but variable content to add into that space. I was recently working on a table for displaying user information and noticed that longer strings were...

  • By
    Introducing MooTools LazyLoad

    Once concept I'm very fond of is lazy loading. Lazy loading defers the loading of resources (usually images) until they are needed. Why load stuff you never need if you can prevent it, right? I've created LazyLoad, a customizable MooTools plugin that...

Discussion

  1. Ron

    Where do we add this php? I am a newbie

  2. Brilliant, thank you!

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!