WooCommerce: Add product to cart with price override?

dcolumbus picture dcolumbus · Sep 8, 2012 · Viewed 67.9k times · Source
$replace_order = new WC_Cart();
$replace_order->empty_cart( true );
$replace_order->add_to_cart( "256", "1");

The above code add product 256 to the Cart 1 time. But the issue I'm having is that I want to be able to completely override the product price... as far as I can tell, the only thing I can do it apply a coupon to the Cart.

Is there a way to completely override the price to something totally custom?

Answer

Ratnakar - StoreApps picture Ratnakar - StoreApps · Sep 8, 2012

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