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.
Opens WPIDE on
Code
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 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.