Jump Straight to a Product When Searching Its SKU
Sends shoppers directly to the product page when what they type in the search box is exactly a product's SKU or code.
Opens WPIDE on
Code
add_action( 'template_redirect', function () {
if ( ! is_search() || is_admin() ) {
return;
}
$term = trim( get_search_query( false ) );
if ( '' === $term || strlen( $term ) > 64 ) {
return;
}
$id = wc_get_product_id_by_sku( $term );
$product = $id ? wc_get_product( $id ) : null;
if ( ! $product || ( ! $product->is_visible() && ! $product->is_type( 'variation' ) ) ) {
return;
}
$url = $product->get_permalink();
if ( $url ) {
wp_safe_redirect( $url );
exit;
}
} );
Notes
Variation SKUs open the parent product with that variation preselected.
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.