The following code allows to show the price per kilo using WooCommerce and ACF by creating a price_per_kilo
custom product field via ACF:
global $product;
$price = $product->get_price();
$weight = $product->get_weight();
$id = $product->get_id();
$value = 1000 * $price / $weight;
update_field('price_per_kilo', $value, $id); // this code updates data for this field
the_field('price_per_kilo', $product->$id ); //show price per kilo
However it shows a lot of digits when the result is not round, do you know how I can limit to two decimal places ?
First here is a mistake in the_field('price_per_kilo', $product->$id );
where $product->$id
should replaced by $id
or $product->get_id()
.
You can use number_format()
to limit the price to 2 decimals, so in your code just replace:
$value = 1000 * $price / $weight;
with:
$value = number_format( 1000 * $price / $weight, 2 );
Or to display a formatted price in WooCommerce with the currency, use wc_price()
formatting price function as follows, replacing:
the_field('price_per_kilo', $product->$id );
with:
echo wc_price( get_field('price_per_kilo', $product->get_id() ) );