简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM