I’m trying to display prices of certain WooCommerce products/variations on a regular page. The reason I can’t type it manually is these prices are changed in real-time by a plugin with a currency rate.
I found this page:
How to get the price of variable product using variation ID?
In my page builder I inserted a code block with this piece of code:
<?PHP
$product_id = ###;
// ### is the product ID
$_product = wc_get_product( $product_id );
echo $_product->get_sale_price();
?>
or this one
<?PHP
$variation_id = ###;
// ### is the variation ID
$_variation = wc_get_product( $variation_id );
echo $_variation->get_sale_price();
?>
They both worked but the displayed numbers had so many decimal places like 2360.8353159978.
(see example screenshot: https://i.imgur.com/7D4Xydu.png)
I would like to round them up to zero like 2360.
The other issue is they are with no tax. I think that’s because I use the price excl. tax on the backend of product pages (Woo shows the price incl. tax on the front end though, which is what I want to achieve here too).
The third issue is numbers don’t the comma for thousands.
The perfect result should be 2,596 because 2,360 + 10% tax = 2,596
I’m very new to PHP and have sought the answer for a long time.
Can anybody kindly give me some suggestions? Any input is appreciated.
2
Answers
I've found the answer to my own question. See the codes below:
You can replace the variation_id with product_id too as long as you can find them.
So I needed to use the wc_price to get the formatted price numbers, which is the way you set the thousand separator and no. of decimal, etc in WooCommerce' General tab. For rounding, since I've created a way to round the numbers in WooCommerce (similar to function.php in the child theme) so wc_price will call and show the rounded result as well.
The format still needs to be tweaked on my WordPress page e.g. I like to remove all decimals so I used array('decimals' => 0) to truncate them.
Text style also needs to be fixed with CSS but I'm not to show that here since it's not relevant to the topic.
Anyway the problem is solved. Hope this code is useful to other people. Again I know very very little about PHP it's just from my searching on Google. Anyone who likes to improve the code please share.
Best, Acon
I’m not sure about the tax, but here is the solution for trimming the decimals: