在Woocommerce 3中更改购物车商品价格

Arc*_*ana 11 php wordpress product cart woocommerce

我正在尝试使用以下功能在购物车中更改产品价格:

    add_action( 'woocommerce_before_shipping_calculator', 'add_custom_price' 
     );
      function add_custom_price( $cart_object ) {
         foreach ( $cart_object->cart_contents as $key => $value ) {
         $value['data']->price = 400;
        } 
     }
Run Code Online (Sandbox Code Playgroud)

它在WooCommerce版本2.6.x中正常工作,但在3.0+版本中不再有效

如何让它在WooCommerce版本3.0+中运行?

谢谢.

Loi*_*tec 39

更新 (2018年9月)

使用WooCommerce 3.0+版,您需要:

这是代码:

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 20, 1);
function add_custom_price( $cart ) {

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

    // Avoiding hook repetition (when using price calculations for example)
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $item ) {
        $item['data']->set_price( 40 );
    }
}
Run Code Online (Sandbox Code Playgroud)

代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中.

此代码经过测试和运行.

注意:您可以将挂钩优先级(或甚20更高)增加1000 2000)使用一些特定的插件或其他自定义时.

有关: