Woocommerce 将价格四舍五入

时间:2021-03-26 09:32:50

标签: 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);
    }

}

2 个答案:

答案 0 :(得分:0)

如您所见 here,看起来它总是会在 zecimals 中发生很小的变化

答案 1 :(得分:0)

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

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

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