更改Woocommerce 3中的购物车项目价格 [英] Change cart item prices in Woocommerce 3

查看:117
本文介绍了更改Woocommerce 3中的购物车项目价格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to change product price in cart using the following function:

    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;
        } 
     }

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

It was working correctly in WooCommerce version 2.6.x but not working anymore in version 3.0+

如何使其在WooCommerce 3.0+版本中正常工作?

How can I make it work in WooCommerce Version 3.0+?

谢谢.

推荐答案

更新 (2018年9月)

使用 WooCommerce 3.0+版,您需要:

  • To use woocommerce_before_calculate_totals hook instead.
  • To use WC_Cart get_cart() method instead
  • To use WC_product set_price() method instead

这是代码:

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 );
    }
}

该代码会出现在您活动的子主题(或主题)的function.php文件中,也可能会出现在任何插件文件中.

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

This code is tested and works.

注意:您可以将挂钩优先级从 20 提升到 1000 (甚至是 2000 ) .

Note: you can increase the hook priority from 20 to 1000 (or even 2000) when using some few specific plugins or others customizations.

相关:

  • Set cart item price from a hidden input field custom price in Woocommerce 3
  • Change cart item prices based on custom cart item data in Woocommerce
  • Set a specific product price conditionally on Woocommerce single product page & cart
  • Add a select field that will change price in Woocommerce simple products

这篇关于更改Woocommerce 3中的购物车项目价格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆