woocommerce - Woocommerce 四舍五入价格
问题描述
我设定了 7,09 的价格,在购物车中显示 7,00。我怎样才能去掉这个舍入?我有自定义变化价格字段。
我的代码:
woocommerce_wp_text_input(
array(
'id' => '_number_field[' . $variation->ID . ']',
'label' => __( 'Aluse hind', 'woocommerce' ),
'desc_tip' => 'true',
'description' => __( 'Sisesta aluse hind.', 'woocommerce' ),
'value' => get_post_meta( $variation->ID, '_number_field', true ),
'custom_attributes' => array(
'step' => 'any',
'min' => '0'
)
)
);
add_filter('woocommerce_product_variation_get_price', 'custom_product_get_price', 10, 2 );
add_filter('woocommerce_show_variation_price', function() { return TRUE;});
function custom_product_get_price( $price, $product ){
if (!empty(get_post_meta( $product->get_id(), '_number_field', true))) {
return get_post_meta( $product->get_id(), '_number_field', true);
} else {
return get_post_meta( $product->get_id(), '_price', true);
}
}
解决方案
这不是一个四舍五入的问题。您只是将字符串作为价格传递,浮点转换会截断小数。
如果自定义字段的值_number_field
使用逗号,则必须将其转换为数值(浮点数),将逗号替换为小数点。
在您的日志文件中,您还将找到通知:Notice: A non well formed numeric value encountered
.
此外,woocommerce_product_variation_get_price
钩子已经返回_price
产品变体的元数据,因此不需要 else 声明。
您可以像这样优化custom_product_get_price
功能:
add_filter('woocommerce_product_variation_get_price', 'custom_product_get_price', 10, 2 );
function custom_product_get_price( $price, $product ) {
if ( ! empty( get_post_meta( $product->get_id(), '_number_field', true) ) ) {
$new_price = get_post_meta( $product->get_id(), '_number_field', true );
$new_price = (float) str_replace( ',', '.', $new_price );
}
if ( isset($new_price) ) {
return $new_price;
} else {
return $price;
}
}
该代码已经过测试并且可以工作。
推荐阅读
- delphi - 如何使用 Altium 脚本系统删除 Altium PCB 库中的 PCB 对象?
- random - 如何从 Tensorflow Probability: tfp.mcmc.sample_chain 中获取可重现的样本?
- sql - 如何使用 SAS、SQL 或伪代码创建更准确的组 ID
- python - Matplotlib:添加多个箭头以产生结果箭头
- docker - 当一个容器旋转另一个容器时,docker 在容器之间共享数据
- f# - 使用 F# ExcelProvider 处理多行标题和隐藏列
- php - count():参数必须是第8行实现Countable的数组或对象
- javascript - Ajax 与 Node.js/Express 404
- spring-boot - 未调用 Spring Batch 跳过策略
- python - matplotlib 中使用颜色图的条形图