# Find Products by SKU in the Site Search

> Lets shoppers type a SKU into the regular search box and find the matching product, including SKUs of variations.

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

## Code

```php
add_filter( 'posts_search', function ( $search, $query ) {
    global $wpdb;

    if ( is_admin() || ! $query->is_main_query() || ! $query->is_search() || '' === $search ) {
        return $search;
    }

    $term = trim( (string) $query->get( 's' ) );

    if ( '' === $term || strlen( $term ) > 100 ) {
        return $search;
    }

    $id = wc_get_product_id_by_sku( $term );

    if ( ! $id ) {
        return $search;
    }

    $product = wc_get_product( $id );
    $id      = $product && $product->get_parent_id() ? $product->get_parent_id() : $id;

    // Wrap the original search clause and add the SKU match to it.
    $inner = preg_replace( '/^\s*AND\s*/', '', $search, 1, $replaced );

    if ( ! $replaced ) {
        return $search;
    }

    return ' AND ( ( ' . $inner . ' ) ' . $wpdb->prepare( "OR {$wpdb->posts}.ID = %d", $id ) . ' ) ';
}, 10, 2 );
```

## Notes

Matches exact SKUs. Variation matches return the parent product.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Find Products by SKU in the Site Search" 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/
