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

21

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

    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+版本中不再工作。

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

谢谢。


2个回答

62

2021更新 (处理小型购物车自定义商品价格)

对于 WooCommerce 3.0+版本 您需要:

以下是代码:

// Set custom cart item price
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 1000, 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 | optional)
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        $cart_item['data']->set_price( 40 );
    }
}

并且对于迷你购物车 (更新):

// Mini cart: Display custom price 
add_filter( 'woocommerce_cart_item_price', 'filter_cart_item_price', 10, 3 );
function filter_cart_item_price( $price_html, $cart_item, $cart_item_key ) {

    if( isset( $cart_item['custom_price'] ) ) {
        $args = array( 'price' => 40 );

        if ( WC()->cart->display_prices_including_tax() ) {
            $product_price = wc_get_price_including_tax( $cart_item['data'], $args );
        } else {
            $product_price = wc_get_price_excluding_tax( $cart_item['data'], $args );
        }
        return wc_price( $product_price );
    }
    return $price_html;
}

将代码放在您的活动子主题(或活动主题)的functions.php文件中。

此代码经过测试,可正常工作 (仍然适用于WooCommerce 5.1.x)

注意:当使用一些特定插件或其他自定义时,您可以将挂钩优先级20增加到1000(甚至是2000

相关:


嗨,#LoicTheAztec,这个解决方案对于硬编码的值是正确的,但对于动态值不起作用。 - Archana
我们如何使这些值动态化? - Asif Rao
@AsifRao 你需要什么,能否请你更具体地说明一下? - LoicTheAztec
我想使用add_to_cart()为添加到购物车中的产品添加自定义价格; 因此需要产品ID和我计算出的自定义价格。在这个钩子中,我如何获取这些值? - Asif Rao
@AsifRao 很抱歉,但这个答案与 add_to_cart() 功能无关... 你应该需要在 StackOverFlow 上提一个新问题... - LoicTheAztec

1
使用 WooCommerce 版本 3.2.6,如果将优先级提高到 1000,则 @LoicTheAztec 的答案对我有效。 我尝试了优先级值为 10、99 和 999,但是我的购物车中的价格和总价没有变化(尽管我能够用 get_price() 确认 set_price() 实际上已经设置了商品价格)。我有一个自定义钩子,向我的购物车添加费用,并且我正在使用一个第三方插件添加产品属性。 我怀疑这些 WooCommerce "add-ons" 引入了延迟,需要我延迟自定义操作。

1
我正在使用WC-Fields-Factory插件版本2.0.6添加自定义产品属性。我在插件目录中搜索了999,并发现插件中有多个实例,其中操作优先级为999。我猜测,在我的情况下,这就是为什么我需要1000的优先级的原因。 - Tony

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接