Limit WordPress Search results to Custom Post Type (and dont break your app)

So recently I was asked to limit search results to a particular custom post type, for example a woocommerce product, here is how I did it:

[dt_code]

// Change search function globally to search only post, page and portfolio post types
function prefix_limit_post_types_in_search( $query ) {
if ( $query->is_search ) {
$query->set( ‘post_type’, array( ‘product’ ) );
$query->set( ‘meta_query’, array(
array(
‘key’ => ‘_stock_status’,
‘value’ => ‘instock’
),
) );
}
return $query;
}
add_filter( ‘pre_get_posts’, ‘prefix_limit_post_types_in_search’ );

[/dt_code]

Essentially all I am doing here is changing the query_vars when doing a search to limit the results to products and only those that have a meta key (_stock_status) set to ‘instock’. Pretty simple stuff.

Now this will produce some unwanted side affects, one of them being that the wordpress’ media search stops working!

Anyways after a bit of head scratching I realised that the problem was stemming from this query. Easy fix, just commented out the add_filter part and the media search works again.

So how do we fix this issue but still limit our search results on the front end to our custom post type? Well I realised that the only time we want to get results from our custom post type is when we are on the front end of the site. So the fix is simple:

[dt_code]

// Change search function globally to search only post, page and portfolio post types
function prefix_limit_post_types_in_search( $query ) {
if ( $query->is_search && !is_admin() ) {
$query->set( ‘post_type’, array( ‘product’ ) );
$query->set( ‘meta_query’, array(
array(
‘key’ => ‘_stock_status’,
‘value’ => ‘instock’
),
) );
}
return $query;
}
add_filter( ‘pre_get_posts’, ‘prefix_limit_post_types_in_search’ );

[/dt_code]

Notice the !is_admin() in our if statement? This limits our search function to the front end only.

About The Author

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top