Change cart item prices in Woocommerce 3

Archana picture Archana · Apr 10, 2017 · Viewed 28.4k times · Source

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.

Answer

LoicTheAztec picture LoicTheAztec · Apr 10, 2017

Update (November 2020)

With WooCommerce version 3.0+ you need:

Here is the code:

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 9999, 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 );
    }
}

And for Mini cart: Also change WooCommerce Minicart item price based on product custom field

Code goes in functions.php file of your active child theme (or active theme).

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

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

Related: