Change cart item prices in Woocommerce 3

家住魔仙堡 提交于 2019-11-26 04:28:13

问题


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

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

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

Thanks.


回答1:


Update (September 2018)

With WooCommerce version 3.0+ you need:

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

Here is the code:

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

The Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.

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

Related:

  • 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



回答2:


With WooCommerce version 3.2.6, @LoicTheAztec's answer works for me if I increase the priority to 1000.

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 1000, 1);

I tried priority values of 10,99 and 999 but the price and total in my cart did not change (even though I was able to confirm with get_price() that set_price() had actually set the price of the item.

I have a custom hook that adds a fee to my cart and I'm using a 3rd party plugin that adds product attributes. I suspect that these WooCommerce "add-ons" introduce delays that require me to delay my custom action.



来源:https://stackoverflow.com/questions/43324605/change-cart-item-prices-in-woocommerce-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!