How to Modify the WordPress Query to Exclude Specific Categories

Jens R Jan 1, 2025 Query Modification
How can I stop certain types of posts from showing up on my blog page?
What code can I use to modify the WordPress main query to exclude posts from specific categories on my homepage or archive pages?
Andy answered Jan 1, 2025

Method 1: Using pre_get_posts Filter (Recommended Solution)

Add this code to your theme's functions.php file or a custom functionality plugin. This method modifies the main query before it runs:

function exclude_categories_from_blog( $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        // Add category IDs you want to exclude
        $exclude_cats = array( 4, 7, 12 );
        $query->set( 'category__not_in', $exclude_cats );
    }
}
add_action( 'pre_get_posts', 'exclude_categories_from_blog' );

Method 2: Using Category Parameters in WP_Query

If you're building a custom query in your template files, use this approach:

$args = array(
    'post_type' => 'post',
    'category__not_in' => array( 4, 7, 12 ), // Replace with your category IDs
    'posts_per_page' => get_option( 'posts_per_page' )
);
$custom_query = new WP_Query( $args );

if ( $custom_query->have_posts() ) :
    while ( $custom_query->have_posts() ) : $custom_query->the_post();
        // Your loop content here
    endwhile;
    wp_reset_postdata();
endif;

Method 3: Using Category Slugs Instead of IDs

If you prefer using category slugs, add this to functions.php:

function exclude_categories_by_slug( $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $cats_to_exclude = array( 'news', 'events' ); // Replace with your category slugs
        $exclude_ids = array();
        
        foreach( $cats_to_exclude as $slug ) {
            $cat = get_category_by_slug( $slug );
            if( $cat ) {
                $exclude_ids[] = $cat->term_id;
            }
        }
        
        $query->set( 'category__not_in', $exclude_ids );
    }
}
add_action( 'pre_get_posts', 'exclude_categories_by_slug' );

Plugin Solutions

If you prefer a plugin solution, here are reliable options:

  1. Ultimate Category Excluder - Simple plugin to exclude categories from home page, feeds, and archives
  2. Post Types Order - Offers category exclusion along with post ordering features

Important Notes:

  • Replace the category IDs (4, 7, 12) or slugs with your actual category IDs/slugs
  • To find your category IDs, go to Posts → Categories in WordPress admin and hover over the category links
  • The pre_get_posts method is the most efficient as it modifies the main query without creating additional queries
  • These solutions work for the blog page, archives, and search results
  • Test thoroughly after implementation, especially if using with custom themes or page builders