How To Limit WordPress Search Results to Specific Post Types

How To Limit WordPress Search Results to Specific Post Types

This short tutorial will show you how to limit WordPress search results to specific post types when creating WordPress sites that have multiple custom post types added. To acheive this functionality we will use the WordPress pre_get_posts filter to hook into the default WordPress search query.

Add this code below to your themes functions.php to limit your search query to the post types of Post and Page only.

function wpshock_search_filter( $query ) {
    if ( $query->is_search ) {
        $query->set( 'post_type', array('post','page') );
    }
    return $query;
}
add_filter('pre_get_posts','wpshock_search_filter');

The important part of the code above where you an add or remove post types is below.

array('post','page')

If for example you created a custom WordPress post type with the name of books and wanted this post type to be included in the search results you would alter the code like this example below.

array('post','page', 'books')
Tagged: , , ,

Author:  | Website: http://stuartduff.com/ | Twitter: Follow Stuart

Stuart Duff is the founder of WPShock and works at WooThemes as a support ninja. In his spare time you can find Stuart Developing plugins and themes for WordPress, discussing WordPress or drinking tea.

  1. Tutorials says:

    Very useful tip, should help to look more professional. Thanks Stuart

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>