WordPress Tutorial: Restricting WordPress Searches

While WordPress comes packed with some amazing features, it can be challenging to uncover the finer details, as the WordPress codex and support forums contain a vast array of information that can be difficult to navigate. Having worked with WordPress for quite some time, I have found that manipulating WordPress core hooks and actions can solve a lot of issues without having to rely on plugins.

One of the most powerful filters in WordPress is named pre_get_posts. This filter allows you to alter the underlying SQL query used for retrieving data from the database. In order to limit search results to a set of post types we can use a simple function to set the query. 

To achieve this restriction, you will need to add the following code to your theme's functions.php file:

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

This code will restrict WordPress searches to only include the specified post types, including pages, posts, and attachments, in addition to the custom post type example_post_type. This technique can help to streamline your search results and make them more relevant to your website visitors.

It's important to note that you can customise this code to fit your unique needs. For example, if you have several custom post types that you would like to include in your search results, you can simply add them to the array. On the other hand, if you would like to exclude specific post types, you can do so by removing them from the array.

By following this tutorial and customising the code to meet your specific requirements, you can streamline your website's search functionality and provide your users with more accurate and relevant results.