【问题标题】:How to set custom product price after add to cart in WooCommerce? [duplicate]在 WooCommerce 中添加到购物车后如何设置自定义产品价格? [复制]
【发布时间】:2021-07-11 05:38:51
【问题描述】:

我需要在计算后设置自定义产品价格。我正在执行下面的代码,它运行良好,但它只是从整数中获取第一个数字

add_filter('woocommerce_add_cart_item_data','wdm_add_item_data',1,10);
function wdm_add_item_data($cart_item_data, $product_id) {

    global $woocommerce;
    $new_value = array();
    $new_value['_custom_options'] = '678';

    if(empty($cart_item_data)) {
        return $new_value;
    } else {
        return array_merge($cart_item_data, $new_value);
    }
}

话虽如此,自定义价格只是设置为 6,应该是 678。 太奇怪了,有人知道为什么以及如何解决吗? 非常感谢。

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    您使用woocommerce_add_cart_item_data 添加自定义元是正确的,但您没有将自定义价格设置为产品价格。

    function wdm_add_item_data( $cart_item_data, $product_id ) {
        
        $cart_item_data[ "_custom_options" ] = 678
        return $cart_item_data;
    }
    add_filter( 'woocommerce_add_cart_item_data', 'wdm_add_item_data', 10, 2 );
    

    使用woocommerce_before_calculate_totals 动作挂钩来设置 为购物车中的产品定制价格。

    function woocommerce_custom_price_to_cart_item( $cart_object ) {  
        foreach ( $cart_object->cart_contents as $key => $value ) {
            if( isset( $value["_custom_options"] ) ) {
                $value['data']->set_price($value["_custom_options"]);
            }
        }  
    }
    add_action( 'woocommerce_before_calculate_totals', 'woocommerce_custom_price_to_cart_item', 10 );
    

    【讨论】:

    • 是的,非常感谢。它帮助了我。
    • 是的。我这样做了。再次感谢。
    猜你喜欢
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    • 2015-05-27
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多