在 WooCommerce + ACF 中将每公斤自定义价格限制为小数点后两位
Limit custom price per kilo to 2 decimals in WooCommerce + ACF
以下代码允许通过 ACF 创建 price_per_kilo
自定义产品字段,使用 WooCommerce 和 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
但是当结果不是四舍五入时它显示很多数字,你知道我如何限制到小数点后两位吗?
首先这里是 the_field('price_per_kilo', $product->$id );
中的一个错误,其中 $product->$id
应该替换为 $id
或 $product->get_id()
。
您可以使用 number_format()
将价格限制为 2 位小数,因此在您的代码中只需替换:
$value = 1000 * $price / $weight;
与:
$value = number_format( 1000 * $price / $weight, 2 );
或者要在 WooCommerce 中使用货币 显示 格式化价格,请使用 wc_price()
格式化价格函数,替换为:
the_field('price_per_kilo', $product->$id );
与:
echo wc_price( get_field('price_per_kilo', $product->get_id() ) );
以下代码允许通过 ACF 创建 price_per_kilo
自定义产品字段,使用 WooCommerce 和 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
但是当结果不是四舍五入时它显示很多数字,你知道我如何限制到小数点后两位吗?
首先这里是 the_field('price_per_kilo', $product->$id );
中的一个错误,其中 $product->$id
应该替换为 $id
或 $product->get_id()
。
您可以使用 number_format()
将价格限制为 2 位小数,因此在您的代码中只需替换:
$value = 1000 * $price / $weight;
与:
$value = number_format( 1000 * $price / $weight, 2 );
或者要在 WooCommerce 中使用货币 显示 格式化价格,请使用 wc_price()
格式化价格函数,替换为:
the_field('price_per_kilo', $product->$id );
与:
echo wc_price( get_field('price_per_kilo', $product->get_id() ) );