Home > Mobile >  Wordpress Shortcode Not Returning Expected Result
Wordpress Shortcode Not Returning Expected Result

Time:07-20

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"]

CodePudding user response:

This worked for me in testing.

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' => '',
        ),
        $atts,
        'db_wc_product_price'
    );

    if ( empty( $atts['id'] ) ) {
        return 'no id';
    }

    $product = wc_get_product( $atts['id'] );

    if ( ! $product ) {
        return 'No product found';
    }
    return get_woocommerce_currency_symbol() . number_format( $product->get_price(), 2 );
}

CodePudding user response:

wc_get_product was called incorrectly. You are trying to call the shortcode before woocommerce init.

Here is the related answer Display product prices with a shortcode by product ID in WooCommerce

woocommerce_init, woocommerce_after_register_taxonomy, woocommerce_after_register_post_type

These actions should be run before your shortcode run.

  • Related