Get the Url of a product from its SKU in WooCommerce

5.3k views Asked by At

The question is simple, if I know the SKU of my product and nothing else, how can I retrieve the url/permalink to that item?

This is commonly useful for third party integration.

2

There are 2 answers

1
Bilal Hussain On
     function get_product_by_sku( $sku ) {

       global $wpdb;

     $product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $sku ) );

     $url = get_permalink( $product_id );

     return $url;
        }

hope this help.

Thanks

0
LoicTheAztec On

You can use dedicated function wc_get_product_id_by_sku( $sku ) where $sku argument is the SKU of your product.

It will return the product ID.

Reference: Function wc_get_product_id_by_sku

Then to get the permalink:

$sku = 'Gh2563'; // SKU example to be replaced by the real SKU of the product
$product_id = wc_get_product_id_by_sku( $sku );
$link = get_permalink( $product_id );