更新到WC 3.0.1后,woocommerce_before_calculate_totals钩子停止工作

时间:2017-04-07 18:53:25

标签: woocommerce

我已从2.6.14更新到WC 3.0.1 我的原始代码如下:

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );

function add_custom_price( $cart_object ) {
    $custom_price = 10; // This will be your custome price  
    foreach ( $cart_object->cart_contents as $key => $value ) {
        $value['data']->price = $custom_price;
    }
}

不再更新购物车或迷你车的价格。

4 个答案:

答案 0 :(得分:8)

对于最新版本的Woocommerce(3.0.1)中的购物车价格,请尝试在woocommerce中使用set_price($ price)功能,这将有所帮助。 Source here

add_action( 'woocommerce_before_calculate_totals', 'woocommerce_pj_update_price', 99 );

function woocommerce_pj_update_price() {

    $custom_price = $_COOKIE["donation"]; // This will be your custom price  
    $target_product_id = 413; //Product ID

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

        if($cart_item['data']->get_id() == $target_product_id){

            $cart_item['data']->set_price($custom_price);
        }

    }

}

答案 1 :(得分:0)

稍作改动:

//OLD:
$value['data']->price = $custom_price;

//NEW:
$value['data']->set_price( $custom_price );

function add_custom_price( $cart_object ) {
    $custom_price = 10; // This will be your custome price  
    foreach ( $cart_object->cart_contents as $key => $value ) {
        $value['data']->set_price( $custom_price );
    }
}

答案 2 :(得分:0)

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 10, 1);
function add_custom_price( $cart_obj ) {

    //  This is necessary for WC 3.0+
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    foreach ( $cart_obj->get_cart() as $key => $value ) {
        $value['data']->set_price( 40 );
    }
 }

如果我设置$ value ['data'] - > set_price(40)工作正常,但是:

 foreach ( $cart_obj->get_cart() as $key => $value ) {
            $price = 50;
            $value['data']->set_price( $price );
 }

答案 3 :(得分:0)

好吧,问题在于您直接通过$value['data']->price致电价格。
做到:

$value['data']->get_price()

我认为您的问题将得到解决