Search WooCommerce Products by SKU
Lets shoppers find products by typing their SKU into the store search, including SKUs of individual variations.
Opens WPIDE on
Code
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 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.