Wordpress Snippets

Limit Search Results For Specific Post Types

If you’re using a lot of custom post types then there are very good chance that your search results are displaying some content that you don’t want to display. Even sometimes you don’t want to include pages in search results too.

So here is a simple solution to your problem. Adding this WordPress code snippet to your theme’s functions.php will allow you to search in specific post types.

In this example we are restricting our search to display results only from post type movies.

// limit search results for a specific post type
function wcs_limit_search( $query ) {
    if ( $query->is_search && !is_admin() ) {
        $query->set( 'post_type', 'movies' );
    }
    return $query;
}
add_filter( 'pre_get_posts', 'wcs_limit_search' );

If you want to limit search results for multiple post types then you can modify above code snippet and insert a array of post types. Now we are limiting our search to show posts from movies and music post types

// limit search results for specific post types
function wcs_limit_search( $query ) {
    if ( $query->is_search && !is_admin() ) {
        $query->set( 'post_type', array( 'movies', 'music' ) );
    }
    return $query;
}
add_filter( 'pre_get_posts', 'wcs_limit_search' );

Hire Us. Or just say Hi!
Need a job? Apply to get one.