Customizing Search Results

In certain situations, you may want to customize your search results by post type – maybe you want your search results sitewide to display only products or only blog posts, etc.
To achieve this, you would attach the following code snippet to the bottom of your theme’s functions.php file:

// Set search results to display only 'product' post type results
if ( !is_admin() ) {
function searchfilter($query) {
    if ($query->is_search && !is_admin() ) {
        $query->set('post_type',array('product'));
    }
return $query;
}
add_filter('pre_get_posts','searchfilter');
}

Notice that the key argument is ‘product’. You can use the following keys to determine which type of posts to display:
• ‘product’ = Products
• ‘post’ = Posts (blog articles)
• ‘page’ = Static pages
You can include multiple post types by setting the arguments line to something like:
$query->set(‘post_type’,array(‘product’,’page’));

You can also use this with any other custom post type your site uses – for example, if you had theProjects by WooThemes plugin, you could use ‘project’ to filter by Projects. You can see how to find your post type in the image below:
post-type

we’re excluding pages with IDs 10, 11, 20, and 105 from the search results. You will need to change these numbers to match the IDs of the pages you want to exclude.
The WP_Query class in WordPress is a powerful tool we have at our disposal for customizing the content shown on our sites.

function jp_search_filter( $query ) {
  if ( ! $query->is_admin && $query->is_search && $query->is_main_query() ) {
    $query->set( 'post__not_in', array( 10,11,20,105 ) );
  }
}
add_action( 'pre_get_posts', 'jp_search_filter' );

Check out the WP_Query documentation to see all the things it can do.

Keep in mind that this is a sitewide effect. This will not impact search results done through your WordPress dashboard, only front-end searches. To remove, simply comment out the code or remove it from your functions.php file. As always, make sure you have a backup before editing!