WooCommerce: Add product to cart with price override? WooCommerce: Add product to cart with price override? wordpress wordpress

WooCommerce: Add product to cart with price override?


Here is the code for overriding price of product in cart

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;        // for WooCommerce version 3+ use:         // $value['data']->set_price($custom_price);    }}

Hope it will be useful...


You need to introduce an if statement for checking product id, in above code:

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );function add_custom_price( $cart_object ) {    $custom_price = 10; // This will be your custome price      $target_product_id = 598;    foreach ( $cart_object->cart_contents as $value ) {        if ( $value['product_id'] == $target_product_id ) {            $value['data']->price = $custom_price;        }        /*        // If your target product is a variation        if ( $value['variation_id'] == $target_product_id ) {            $value['data']->price = $custom_price;        }        */    }}

Add this code anywhere and make sure that this code is always executable.

After adding this code, when you'll call:

global $woocommerce; $woocommerce->cart->add_to_cart(598);

Only this product will be added with overridden price, other products added to cart will be ignored for overriding prices.

Hope this will be helpful.


I have tried all above code samples and latest woocommerce 3.0 is not support any of the above example. Use below code and working perfectly for me.

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );function add_custom_price( $cart_object ) {    $custom_price = 10; // This will be your custom price      foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {        $cart_item['data']->set_price($custom_price);       }}