Display product prices with a shortcode by product ID in WooCommerce

前端 未结 4 1758
迷失自我
迷失自我 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:38

    Updated (takes into account if your prices are displayed with or without taxes)

    With Woocommerce there is already formatting price function wc_price() that you can use in your code. Also you need to get the sale price

    To get this working when there is a sale price or without it try this code (commented):

    function custom_price_shortcode_callback( $atts ) {
    
        $atts = shortcode_atts( array(
            'id' => null,
        ), $atts, 'product_price' );
    
        $html = '';
    
        if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
            // Get an instance of the WC_Product object
            $product = wc_get_product( intval( $atts['id'] ) );
    
            // Get the product prices
            $price         = wc_get_price_to_display( $product, array( 'price' => $product->get_price() ) ); // Get the active price
            $regular_price = wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) ); // Get the regular price
            $sale_price    = wc_get_price_to_display( $product, array( 'price' => $product->get_sale_price() ) ); // Get the sale price
    
            // Your price CSS styles
            $style1 = 'style="font-size:40px;color:#e79a99;font-weight:bold;"';
            $style2 = 'style="font-size:25px;color:#e79a99"';
    
            // Formatting price settings (for the wc_price() function)
            $args = array(
                'ex_tax_label'       => false,
                'currency'           => 'EUR',
                'decimal_separator'  => '.',
                'thousand_separator' => ' ',
                'decimals'           => 2,
                'price_format'       => '%2$s %1$s',
            );
    
            // Formatting html output
            if( ! empty( $sale_price ) && $sale_price != 0 && $sale_price < $regular_price )
                $html = "" . wc_price( $regular_price, $args ) . " " . wc_price( $sale_price, $args ) . ""; // Sale price is set
            else
                $html = "" . wc_price( $price, $args ) . ""; // No sale price set
        }
        return $html;
     }
     add_shortcode( 'product_price', 'custom_price_shortcode_callback' );
    

    Code goes in function.php file of your active child theme (or theme) or also in any plugin file.


    USAGE (for example product ID 37):

    [product_price id="37"]
    

    This code is tested and works. You will get this:

提交回复
热议问题