5
votes

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.

4
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.helgatheviking
Thanks helgatheviking, Could you please provide an example for getting and setting price of product ?Gurvir Singh
Look at set_price() in the sourcehelgatheviking
Please write out a complete answer for future visitors.helgatheviking

4 Answers

9
votes

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

    }

}
0
votes

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
votes
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
votes

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