1

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.

Miuri
  • 13
  • 1
  • 4

1 Answers1

2

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');
Antony Thompson
  • 1,608
  • 1
  • 13
  • 22
  • is it possible to get the regular price of the outputed product_id? – Miuri Dec 02 '15 at 11:29
  • Woocommerce have great documentation. Check out the `get_regular_price` method on the product class. https://docs.woothemes.com/wc-apidocs/class-WC_Product.html#_get_regular_price – Antony Thompson Dec 02 '15 at 19:29
  • Thanks Antony, i have alredy read this and alot of other. But my problem is that i need to get out the regular price of the returned $product_id. So far if i use get_regular_price(); it returns me the price of the current_product this shortcode is used on. The Question is how to get the regular price out of the returned $product_id in this function. – Miuri Dec 03 '15 at 09:41
  • It's quite simple... `$new_product = new WC_Product($product_id); $price = $new_product->get_regular_price();` – Antony Thompson Dec 03 '15 at 17:53