Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I've tried the code below to grab the cat ID for one of my categories (watch-isatv) and exclude all of the posts in that category. However, the posts are not being excluded. What is wrong with the code?

function excludeCat($query) {
    if ( $query->is_home ) {
        $catid = get_cat_ID('watch-isatv');
        $query->set('cat', '-'.$catid);
    }
    return $query;
}
add_filter('pre_get_posts', 'excludeCat');
share|improve this question

2 Answers 2

Technically, pre_get_posts is an action, not a filter, and you don't need to return anything and $query is passed in by reference, but that code should nonetheless work. Cleaned up it would be:

function excludeCat($query) {
    if ( $query->is_home ) {
        $catid = get_cat_ID('watch-isatv');
        $query->set('cat', '-'.$catid);
    }
}
add_action('pre_get_posts', 'excludeCat');

There are several potential points of failure though.

  1. You are adding the filter after the main query has run. You must add that filter before the main query. functions.php should work but adding that code in your other theme template files, like archive.php or home.php won't. The main query has already executed.
  2. $query->is_home isn't what you expect or need it to be. Add var_dump($query->is_home); to your code and load your page(s). Make sure it is true where you need it to be and false otherwise.
  3. The slug, not the human readable name, used with get_cat_ID() is incorrect.

I'd put my money on #1 being the problem.

share|improve this answer

Add this code to your child themes functions file & replace 007 with the I.D for the category of posts you want to exclude from the home page.

function wpsites_exclude_category_home( $query ) {
if ( $query->is_home() && !is_admin() && $query->is_main_query() ) {
    $query->set( 'cat', '-007' );
    }
}
add_action( 'pre_get_posts', 'wpsites_exclude_category_home' );
share|improve this answer
    
I should have mentioned this beforehand, but I want to be able to use the slug instead of the ID. Would it be possible to use your code with the slug? –  Desi Apr 27 at 3:04
    
You might find the answer here codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts –  Brad Dalton Apr 27 at 3:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.