首页 > 解决方案 > 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);
    }

}

标签: woocommerce

解决方案


这不是一个四舍五入的问题。您只是将字符串作为价格传递,浮点转换会截断小数。

如果自定义字段的值_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;
    }
    
}

该代码已经过测试并且可以工作。


推荐阅读