3

i'm using this method in combination with an ajax call to set a product from a configurator to my cart:

$woocommerce->cart->add_to_cart($p_id, $p_quantity, $p_var_id, $p_var_name);

How can i use this method to set a calculated custom price? Is it possible?

Greetings,

Marvin

1
  • I tried last week but I could not. I will follow this question.
    – sakarya
    Commented Nov 2, 2017 at 22:23

1 Answer 1

12

Currently there is no straight way to add custom price to product which is added through function $woocommerce->cart->add_to_cart (Documentation) but we have a bypass way that i explain in code below

global $woocommerce;
$custom_price = 1000;
// Cart item data to send & save in order
$cart_item_data = array('custom_price' => $custom_price);   
// woocommerce function to add product into cart check its documentation also 
// what we need here is only $product_id & $cart_item_data other can be default.
$woocommerce->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation, $cart_item_data );
// Calculate totals
$woocommerce->cart->calculate_totals();
// Save cart to session
$woocommerce->cart->set_session();
// Maybe set cart cookies
$woocommerce->cart->maybe_set_cart_cookies();

in your functions file you can place below code

 function woocommerce_custom_price_to_cart_item( $cart_object ) {  
    if( !WC()->session->__isset( "reload_checkout" )) {
        foreach ( $cart_object->cart_contents as $key => $value ) {
            if( isset( $value["custom_price"] ) ) {
                //for woocommerce version lower than 3
                //$value['data']->price = $value["custom_price"];
                //for woocommerce version +3
                $value['data']->set_price($value["custom_price"]);
            }
        }  
    }  
}
add_action( 'woocommerce_before_calculate_totals', 'woocommerce_custom_price_to_cart_item', 99 );

and you are good to go

4
  • Excellent! It solved my problem. Thanks Commented Jul 9, 2020 at 12:14
  • and how to show cart_item_data in cart page ? as well as order email and order history page ? Commented Sep 3, 2020 at 12:03
  • @RahulShinde please follow this link stackoverflow.com/questions/54505642/…
    – AHSAN KHAN
    Commented Sep 3, 2020 at 12:34
  • By implementing above code it works for custom price but for other product it is setting price to 0. Do you have any idea ? Commented Apr 4 at 8:11

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