PraviM
PraviM

Reputation: 31

Get the Url of a product from its SKU in WooCommerce

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.

Upvotes: 3

Views: 5652

Answers (2)

LoicTheAztec
LoicTheAztec

Reputation: 253901

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 );

Upvotes: 3

Bilal Hussain
Bilal Hussain

Reputation: 1011

     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

Upvotes: 0

Related Questions