# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [WooCommerce](https://wpide.com/library/category/woocommerce/)
- Requires: WooCommerce
- Tags: woocommerce, search, stock
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/woo-hide-out-of-stock-from-search/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Hide Out-of-Stock Products From Search Results" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
