Answer the question
In order to leave comments, you need to log in
Changing the price of an item when adding to cart?
Hello. I'm having a problem changing the price of an item when adding it to my cart.
So: when adding to the cart, I send an Ajax request to the server, which accepts the new price of the product and writes it to cookies:
function add_constructor_card(){
$product_id = 9570;
setcookie('add_custom_price', (int)$_POST['price'], time() + 60 * 60 * 24 * 2, '/');
setcookie('constructor_sostav', $_POST['name'], time() + 60 * 60 * 24 * 2, '/');
wp_die();
}
add_action('wp_ajax_add_constructor_card', 'add_constructor_card');
add_action('wp_ajax_nopriv_add_constructor_card', 'add_constructor_card');
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
function add_custom_price( $cart_object ) {
$new_price = $_COOKIE['add_custom_price'];
$target_product_id = 9570;
foreach ( $cart_object->cart_contents as $key => $value ) {
if ( $value['product_id'] == $target_product_id ) {
$value['data']->set_price($new_price);
}
}
}
Answer the question
In order to leave comments, you need to log in
All right.
Woo does not know about its new price at the time of adding the product. Here it displays the old price.
In the cart, you see this because the next request is already running to display the cart page and your cookie has already been defined.
And the widget does not display changes until the contents of your cart change. This is done to reduce the number of ajax requests and synchronize the widget on all open pages of your site.
In general, you could change the price at the time of adding the product to the cart, then you would not have to fiddle with cookies and make additional ajax requests.
Or you can just add a hidden field to the add_to_cart form and fill it with the new price before submitting. And then in your method, check the data of this hidden field, if there is a price.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question