Here is the scenario: Your WordPress e-commerce website has products, blog posts, and pages. You want to limit the search results to either products or blog posts depending on where the search is initiated (i.e. which search widget is used). Unfortunately, the WordPress search widget displays both the products and blog posts on the search results page. This might be confusing to a customer when searching for a product and getting blog posts mixed into the search results.
This tutorial demonstrates how to use separate widgets for product searches and blog searches.
What’s the Difference Between the WordPress & WooCommerce Search Widgets?
WordPress and WooCommerce offer their own search widgets out of the box. Both are separate and function independently of each other.
Here is the primary difference:
- The WooCommerce search widget will return products matching the search criteria. This means that products will only be displayed in the search results.
- The WordPress search widget will return results for all post types, including products. It will search through every post type and output results for posts, pages, products, etc.
Separating Search Results by Post Type
The solution to determining the post types that will be allowed in the search results is to create a function that hooks into pre_get_posts.
Because the WooCommerce search widget is already setup to output only products, the query for the WordPress search widget is what needs to be modified.
The following steps will walk you through how to separate the search results.
Add the WooCommerce product search widget to the shop sidebar. Depending on how the website is setup, it may be listed as the default sidebar.
Add the WordPress search widget to the blog sidebar.
NOTE: You may need to refer to your theme’s documentation for help with steps 1 & 2.
Copy and paste the following PHP code into your theme’s functions.php file:
NOTE: You can control which post types get removed from the query on line 23. The product post type and page post type are used in this tutorial.
If you are unsure about the name of the post type to remove from the search results, you may need to refer to your theme’s documentation for a list of custom post types.
You can also discover the names of all registered post types by using the WordPress get_post_types function.