search ]

Limit WordPress Search to Specific Post Types

Ever wondered how to limit search results to a specific Custom Post Type? It is simple. We have already seen how to completely disable WordPress search by modifying functions.php. Now we will do something similar to filter our search results.

Add the following code to your functions.php file:

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

Note this line:

$query->set('post_type',array('post','page'));

You can filter search results by changing the values in that array. Search results will now show only pages and posts, but you can change this array to include any post type you want.

Join the Discussion
0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development official logo