Search code examples
phpwordpressgetwoocommerceshortcode

Woocommerce get and display product id by sku


I'm trying to find a way to get the Product ID out of the current Product SKU and to display it via a shortcode. So far I come, but for some reason this code I'm using doesnt get the right ID and I cant figure out why because I am not that well in php.

Solve:

function get_product_id_by_sku_fc( $atts ){
 global $product;

 $atts = shortcode_atts( array(
         'sku'  =>  '',
     ), $atts );

 $product_id = null;
 // get product ID out of the defined SKU in the shortcode [get_product_id_by_sku sku="SKU"]
 if (!empty( $atts['sku'] ) ) {
 $product_id = wc_get_product_id_by_sku( $atts['sku'] );
 $product = wc_get_product( $product_id );
 } else {
   //get product ID out of the current_product sku, shortcode [get_product_id_by_sku]
   $sku = $product->get_sku();
   $product_id = wc_get_product_id_by_sku( $sku );
   $product = wc_get_product( $product_id );

 }
 return $product_id;
}
add_shortcode( 'get_product_id_by_sku', 'get_product_id_by_sku_fc');

Thanks all for help!

PS: If you will have conflicts with the funtion, then just customize the funtion name and the shortcode name.


Solution

  • You need to defined $sku before you use it. Assuming your shortcode looks like this:

    [getpid sku="product-1"]
    

    You should be doing something like this:

    function getproductbysku( $atts ){
        $product_id = null; //or whatever you want to default to.
        if(!empty($atts['sku'])){
            $product_id = wc_get_product_id_by_sku( $atts['sku'] );
        }
        return $product_id;
    }
    add_shortcode( 'getpid', 'getproductbysku');