Redirect SKU from URL directly to specific product variation in WooCommerce

55 views Asked by At

I want to be able to open product page directly from URL by SKU (/?sku=GIVEN_SKU). This code works well, but only for normal products:

add_action('template_redirect', 'sku_url_redirect');
function sku_url_redirect() {
    if (isset($_GET['sku'])) {
        $sku = wc_clean($_GET['sku']);
        $product_id = (int) wc_get_product_id_by_sku($sku);
        if ($product_id>0) {
            wp_safe_redirect(get_permalink($product_id));
            exit;
        }
    }
}

Any idea how to do the same for varations? Every variation has its own SKU and I want to open the product page with given variation preselected.

0

There are 0 answers