How to prevent posts from a particular category to be displayed in WordPress loop

Paste the code below into your functions.php file. Don’t forget to update the code with the category ID you want to exclude (on line 4).

// No "Quick Tips" on the homepage
function preventHomepageTips($query) {
  if($query->is_home() && $query->is_main_query()) {
    $query->set('cat', '-40'); // 40 is Quick Tips's category ID
  }
}
add_action('pre_get_posts', 'preventHomepageTips');

Note that David Walsh, the author of this code, have created a plugin which do the same thing as this snippet.

Thanks to David Walsh for the code!

Leave a Reply

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