# Search WooCommerce Products by SKU

> Lets shoppers find products by typing their SKU into the store search, including SKUs of individual variations.

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

## Code

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

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

    $types = array_filter( (array) $query->get( 'post_type' ) );

    if ( $types && ! array_intersect( $types, array( 'product', 'any' ) ) ) {
        return $search;
    }

    $lookup  = $wpdb->prefix . 'wc_product_meta_lookup';
    $pattern = '/\(' . preg_quote( $wpdb->posts, '/' ) . '\.post_title LIKE (\'(?:[^\'\\\\]|\\\\.)*\')\)/';

    $result = preg_replace_callback( $pattern, function ( $m ) use ( $wpdb, $lookup ) {
        return $m[0] . " OR ({$wpdb->posts}.ID IN (SELECT IF(sku_posts.post_parent > 0, sku_posts.post_parent, sku_posts.ID) FROM {$lookup} sku_lookup INNER JOIN {$wpdb->posts} sku_posts ON sku_posts.ID = sku_lookup.product_id WHERE sku_lookup.sku LIKE {$m[1]}))";
    }, $search );

    return null === $result ? $search : $result;
}, 10, 2 );
```

## Notes

Uses WooCommerce's product lookup table, so it stays fast on large catalogs.

## How to use it

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