Excluding Pages, Posts and Categories from WordPress Search

Categories: Blog, Development, WordPress
Tags: , , , , , ,

Mar 14
2011

From time to time you’ll find that you may want to exclude certain pages, posts or categories from showing up in your search results when using WordPress. For example I wanted to use a WordPress ‘page’ to handle the content of what my 404 page displays. However, I don’t want this page showing up in my search results.

By adding the following code to to the end of your functions.php file in your theme’s directory you can omit whatever you’d like.  If you’re not seeing a functions.php file for your theme you can create one and add the code.

Code

<?php

/* START: Omit Search Filter */

function SearchFilter($query){
  if($query->is_search){

    // List of categories (by ID) to omit when searching. Category ID should be placed in the array.
// 3 - Portfolio
    $categoryOmitArray = array('3');

    // List of pages/posts to omit when searching.  Page/post ID should be placed in the array.
// 7  - 404 - Not Found (page)
// 25 - Resume (protected page)
    $postOmitArray = array('7', '25');

    // Set the pages/posts and categories to exclude in the WP Query
    $query->set('category__not_in', $categoryOmitArray);
    $query->set('post__not_in', $postOmitArray);
  }
  return $query;
}
add_filter('pre_get_posts','SearchFilter');
/* END: Omit Search Filter */

?>

The above code allows you to add your page/post IDs or category IDs to two arrays – allowing you to exclude these from the search results in WordPress.

Exclude Categories

To exclude a category (or categories) you will edit the $categoryOmitArray variable. To exclude multiple categories, add each category ID, in quotes, separated by a comma, like so:

    $categoryOmitArray = array('3', '6', '7');

This excludes categories with IDs 3, 6 and 7 from your search results.

Exclude Pages and/or Posts

For pages and posts it’s the same thing as with categories but you edit the $postOmitArray variable instead.

    $postOmitArray = array('7', '25');

Comments

I find it helpful to put the ID and the page/post or category name in a comment block in the code to make it easier to sort through later.

 

Comments

Leave a comment

 

Leave a comment

Read comments

 



Please do not submit your comment more than once. It will appear once it has been approved.