I'm trying to help someone in creating a wordpress shortcode to fetch the woocommerce price by product id. Below is the code for the function:
add_shortcode('db_wc_product_price', 'db_wc_product_price');
function db_wc_product_price($atts)
{
if (!function_exists('wc_get_product') || !function_exists('get_woocommerce_currency_symbol')) return '';
$atts = shortcode_atts( array(
'id' => null
), $atts, 'db_wc_product_price' );
if (empty($atts['id'])) return 'no id';
$product_id = $atts['id'];
$ret = "id : ".$product_id;
//return $ret;
$product = wc_get_product($product_id);
//$product = wc_get_product(2571);
if (!$product) return 'No product found';
return get_woocommerce_currency_symbol().$product->get_price();
}
This is how I'm calling it:
[db_wc_product_price id='2571']
When I return just the product_id, it is printing correct value. Meaning, id is getting passed correctly. But, when I call wc_get_product($product_id), this return 'No product found'. If I hardcode the value of product_id while calling wc_get_product($product_id), that work fine. What am I doing wrong?
Also, when I call shortcode like this(id in double quote instead of single), it returns 'no id'
[db_wc_product_price id="2571"]