Redirect product SKU from Url to the related product in WooCommerce

I have a WooCommerce store and I would like to basically redirect product SKU from Url to the related product.

So for example for the Url domain.com/product/SKUID, user should be redirected to the following url domain.com/product/product-name or should open up the product page.

I tried this plugin SKU Shortlink for WooCommerce but it ended up breaking my whole website making “too many redirects” issue. Any help is appreciated.

Answer

You don’t need any plugin for that… You can use the following custom simple function hooked in template_redirect action hook, that will redirect from domain.com/product/SKUID to the related WooCommerce product single page.

The code use built in function wc_get_product_id_by_sku() to retrieve the product ID from the product sku.

Then If the product sku matches with an existing product, user is redirected to the product single page.

The code:

add_action('template_redirect', 'sku_product_redirect');
function sku_product_redirect() {
    // Get the sku string from Url
    $sku = get_query_var('product');
    
    if ( ! empty( $sku ) ) {
        // Get the product Id from a product sku string
        $product_id = (int) wc_get_product_id_by_sku( $sku );
        
        if( $product_id > 0 ) {
            wp_safe_redirect( get_permalink($product_id) );
            exit;
        }
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.