Changing a theme’s search function to only show results from woocommerce?

I’m not sure what the job_listing post type refers to – it’s probably part of a feature included in your theme – but in order to limit your search results by post type, the usual way to do this is by hooking into WordPress’ pre_get_posts action in your theme’s functions.php.

Because you’re new to this, a couple of other answers you should have a quick read of first:

Then, armed with that knowledge, we’re going to hook into the pre_get_posts action in our functions.php (you can do this for testing purposes inside your current theme if you like, but as explained in the child themes answer above, your code will be overridden if and when you update your theme, so you should use a child theme to preserve it).

Open your functions.php and add:

add_action( 'pre_get_posts', 'wpse223576_search_woocommerce_only' );

function wpse223576_search_woocommerce_only( $query ) {
  if( ! is_admin() && is_search() && $query->is_main_query() ) {
    $query->set( 'post_type', 'product' );
  }
}

You’ll find more details about how this works in the documentation for pre_get_posts. As explained in the first answer I linked to above, actions and filters (together known as ‘hooks’) allow you to modify the way WordPress core, plugins and themes work by either running code at just the right time or taking input, modifying it, and returning it. This is how the entire pluggable WordPress architecture works.

In this code snippet above, we’re modifying the WordPress query before it runs to query only posts of the type product. Since this is the post type WooCommerce uses internally to store products, you’ll then only get WooCommerce products returned (we also check of course that we’re actually doing a search; that we’re not in the admin panel; and that this is the main query – i.e. not a menu or other query – to make sure we don’t affect any more than we want to).

And that is how you can limit your searches to show WooCommerce product results only.

Leave a Comment