7 February 2018 | Web Development, WordPress

How To Display Search Results For Specific Post Types Only in WordPress

We do use custom post types a LOT in our WordPress projects. It’s the perfect way to fully customise the website for our clients and making the content entry as easy as possible for them.

For a business directory WordPress website with custom post types we’re developing at the moment, we only wanted to perform a site search in the custom posts (the business directory). We didn’t want to display pages or regular blog posts on the search results page.

That’s very easy to do.

We simply modified the main query itself by using the pre_get_posts action.
In the functions.php file we added the following code:

function search_filter($query) {

if ($query->is_search && !is_admin() ) {
$query->set('post_type', 'businesses');
}

return $query;
}

add_filter('pre_get_posts', 'search_filter');

You can filter the search results by changing the values in the array variable. Right now it is set to display the custom post type ‘Businesses’.

Leave a Reply

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

By leaving a comment you agree with the storage and handling of your data by this website. You can learn more about how we handle you comment information in our Privacy Policy. We are using Akismet to reduce comment spam. Learn how they process your comment data.