下面的代码允许通过WooCommerce和ACF创建一个price_per_kilo自定义产品字段来显示每公斤的价格:
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但是,当结果不是圆的时候,它会显示很多数字,你知道我如何能把小数点限制在两位以内吗?
发布于 2021-02-04 09:54:29
首先,在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() ) );https://stackoverflow.com/questions/66043103
复制相似问题