Display product prices with a shortcode by product ID in WooCommerce

前端 未结 4 1754
迷失自我
迷失自我 2021-01-06 11:05

IN WooCommerce I am using the code of this tread to display with a short code the product prices from a defined product ID. But it don\'t really do what I want. Here is that

4条回答
  •  感情败类
    2021-01-06 11:56

    An alternative, if anyone needs simple text output of prices, is the following:

    function wc_price_by_id_shortcode( $atts ) {
        $atts = shortcode_atts( array( 'id' => null, ), $atts, 'bartag' );
    
        if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){ 
            $_product = wc_get_product( $atts['id'] ); 
            $price = wc_price( $_product->get_price() );
          } 
      return $price; 
    } 
    add_shortcode( 'product_price', 'wc_price_by_id_shortcode' );
    

    The shortcode is then [product_price id=XX] (replacing XX with the product id)

    To add styling to the price, add a span class by adding the line:

    $html .= "". $price . "";,

    change the line return $price; to return $html;,

    then add your style formatting to your css as needed.

    (N.B. this only outputs current price, not regular price.)

提交回复
热议问题