John Davidson

php - Limit custom price per kilo to 2 decimals in WooCommerce + ACF

0 comments
Message:


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 ?



My Answer:
>get_price();__$weight = get_field('weight', $product->get_id());__$price_per_kilo = $price / $weight;__echo number_format($price_per_kilo, 2);_

This code calculates the price per kilo by dividing the product price by the weight specified in the custom field 'weight'. The number_format() function is used to limit the result to 2 decimal places.

Rate this post

5 of 5 based on 7789 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us