WooCommerce get product regular and sale price in custom loop

Posted in Code Tips

Recently I was working on a project for a client of mine, I had built them a custom WordPress / WooCommerce website.  The standard related products function just wasn’t working the way they needed it to, they wanted it to only show  in-stock products showing  price, image, title and if the item was on sale. Showing the regular price is simple but showing just the current sale price, without revealing how much the item was before is more tricky.

Getting  the price for regular or sale simply requires a nice simple if statement like this:
[et_bloom_locked optin_id=”optin_4″]

<?php if ( get_post_meta( get_the_ID(), '_sale_price', true) ) { ?>	

<span class="price"><span class="amount">&pound;<?php $saleprice = get_post_meta( get_the_ID(), '_sale_price', true); echo money_format('%.2n', $saleprice) . "\n";  ?></span></span>

<?php } else { ?>
<span class="price"><span class="amount">&pound; <?php $price = get_post_meta( get_the_ID(), '_regular_price', true); echo $price;  ?></span></span>

<?php } ?>

[/et_bloom_locked]

The code above is looking for sale price, if it finds it then it displays it. If  a sale price can’t be found, the regular price will be shown.

You’ll notice on the echo of the sale price that I’m using the money_format. This is to make sure that we always get the full two digits after the decimal (without it, this was a bit hit and miss).

I hope you find this tip useful. If you have any comments or would like to know more, please leave me a comment and I will get back to you.

Image from woothemes.com

 

Share this

AG Bot (BETA) - Not live chat

Ask our bot about our products.

Welcome to our AG Bot, powered by OpenAI and trained on our documents and product pages. By continuing to use this service, please keep in mind:

Your continued use indicates acceptance of these terms. We hope you find our AI Chatbot useful!

Hello! I am AG Bot, how can I help you? (Not live chat)