Bahadori
Bahadori

Reputation: 139

Get product prices to be displayed in WooCommerce 3

I want to display 8 products of category X in my home page

I use the following code to get the 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 which method to use to get regular and sale price.

Upvotes: 7

Views: 19725

Answers (2)

LoicTheAztec
LoicTheAztec

Reputation: 253921

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() ) ) );

Upvotes: 29

Bhumi Shah
Bhumi Shah

Reputation: 9476

You can use, get_sale_price for sale price and get_regular_price for regular price

$product->get_sale_price();

$product->get_regular_price();

Upvotes: 2

Related Questions