Get product prices to be displayed in WooCommerce 3

Bahadori picture Bahadori · Jun 2, 2018 · Viewed 8.5k times · Source

i want to display 8 product of category X in my home page

i use the following code to get products

    <div class="row">
        <?php  
            $args = array(
                'post_type'      => 'product',
                'posts_per_page' => 8,
                'product_cat'    => 'cw'
            );
            $loop = new WP_Query( $args );
            while ( $loop->have_posts() ) : $loop->the_post();
                global $product;
        ?>

        <div class="col-md-3">
            <div class="product">
                <?php echo woocommerce_get_product_thumbnail(); ?>
                <p class="name"><?php echo get_the_title(); ?></p>
                <p class="regular-price"></p>
                <p class="sale-price"></p>
                <a href="<?php echo get_permalink(); ?>" class="more">more info</a>
                <form class="cart" action="<?php echo get_permalink(); ?>" method="post" enctype='multipart/form-data' style="display:inline;">
                    <button type="submit" name="add-to-cart" value="45" class="order">buy</button>
                </form>
            </div>
        </div>

with this i can get products, but i don't know use which method to get regular and sale price

Answer

LoicTheAztec picture LoicTheAztec · Jun 2, 2018

Never use directly get_sale_price(); or get_regular_price(); WC_Product methods to display product prices.

Why? Because you will get the wrong prices in that 2 cases:

  • If you have enter your prices with taxes and you have set the display without taxes
  • If you have enter your prices without taxes and you have set the display with taxes.

So to display product prices correct way is to use wc_get_price_to_display() this way:

// Active price: 
wc_get_price_to_display( $product, array( 'price' => $product->get_price() ) );

//Regular price: 
wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) );

//Sale price: 
wc_get_price_to_display( $product, array( 'price' => $product->get_sale_price() ) );

Now if you want to have the right formatted prices with the currency you will also use wc_price() formatting function this way:

// Active formatted price: 
$product->get_price_html();

// Regular formatted  price: 
wc_price( wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) ) );

// Sale formatted  price: 
wc_price( wc_get_price_to_display( $product, array( 'price' => $product->get_sale_price() ) ) );