Hide Out-of-Stock Products From Search Results
Leaves sold-out products out of the front-end search results while keeping them visible on the shop and category pages.
Opens WPIDE on
Code
add_action( 'pre_get_posts', function ( $query ) {
if ( is_admin() || ! $query->is_main_query() || ! $query->is_search() ) {
return;
}
$meta_query = (array) $query->get( 'meta_query' );
$meta_query[] = array(
'relation' => 'OR',
array(
'key' => '_stock_status',
'value' => 'outofstock',
'compare' => '!=',
),
array(
'key' => '_stock_status',
'compare' => 'NOT EXISTS',
),
);
$query->set( 'meta_query', $meta_query );
} );
Notes
Use the "Hide out of stock items" setting in WooCommerce > Settings > Products > Inventory if you want them hidden everywhere instead.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.