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

查看:31
本文介绍了在 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+?

谢谢.

推荐答案

2021 年更新 (处理迷你购物车自定义商品价格)

使用 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

代码如下:

// 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).

This code is tested and works (still works on WooCommerce 5.1.x).

注意:您可以将钩子优先级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.

相关:

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

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