Post Pic

WordPress snippet: Search within a specific post type only

By default, when a visitor search on your site using WordPress built-in search engine, it search through all post types. But on some websites, you may want to be able to search only within a specific post type. Here’s a handy code snippet to do it.

The following code snippet allows you to modify WordPress search engine to search only within a specific post type. Simply update the code with your post type name on line 4, then paste it into your theme functions.php file.

function SearchFilter($query) {
  if ($query->is_search) {
    // Insert the specific post type you want to search
    $query->set('post_type', 'feeds');
  }
  return $query;
}
 
// This filter will jump into the loop and arrange our results before they're returned
add_filter('pre_get_posts','SearchFilter');

Thanks to Hongkiat for the cool code snippet!

One Response

Oct 04 2012 23:40

Could you also accomplish this using a hidden field in the search form? The problem I have is I want to have slightly different search forms on different sections of my site. I think this function will affect all search forms site-wide?

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required

WP Theme of the week

Sponsored Likebox