5

I have updated to WC 3.0.1 from 2.6.14.
My original code is as follows:

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );

function add_custom_price( $cart_object ) {
    $custom_price = 10; // This will be your custome price  
    foreach ( $cart_object->cart_contents as $key => $value ) {
        $value['data']->price = $custom_price;
    }
}

It is no longer updating the price in cart or minicart.

5
  • You can no longer directly access $product properties. You should see a warning about this in the debug.log if you enabled WP_DEBUG. You must use setters and getters now for product, order, order item, and coupon objects. Apr 7, 2017 at 19:01
  • Thanks helgatheviking, Could you please provide an example for getting and setting price of product ? Apr 7, 2017 at 19:20
  • 1
    Look at set_price() in the source Apr 7, 2017 at 19:23
  • Please write out a complete answer for future visitors. Apr 7, 2017 at 20:16

4 Answers 4

8

For overriding product price on cart in the latest version of Woocommerce (3.0.1) try using set_price( $price ) function in woocommerce this will help. Source here

add_action( 'woocommerce_before_calculate_totals', 'woocommerce_pj_update_price', 99 );

function woocommerce_pj_update_price() {

    $custom_price = $_COOKIE["donation"]; // This will be your custom price  
    $target_product_id = 413; //Product ID

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

        if($cart_item['data']->get_id() == $target_product_id){

            $cart_item['data']->set_price($custom_price);
        }

    }

}
1
  • 3
    3 hours of my time wasted looking for a solution to this. Thanks to you is not 3 days... May 2, 2017 at 11:13
0

Works with a little change:

//OLD:
$value['data']->price = $custom_price;

//NEW:
$value['data']->set_price( $custom_price );

function add_custom_price( $cart_object ) {
    $custom_price = 10; // This will be your custome price  
    foreach ( $cart_object->cart_contents as $key => $value ) {
        $value['data']->set_price( $custom_price );
    }
}
0
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 10, 1);
function add_custom_price( $cart_obj ) {

    //  This is necessary for WC 3.0+
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    foreach ( $cart_obj->get_cart() as $key => $value ) {
        $value['data']->set_price( 40 );
    }
 }

if i set $value['data']->set_price( 40 ) work fine, but:

 foreach ( $cart_obj->get_cart() as $key => $value ) {
            $price = 50;
            $value['data']->set_price( $price );
 }
0

Well, the problem is you are calling price directly at $value['data']->price.
Make it:

$value['data']->get_price()

and I think you problem will be fixed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.