H
H
hellion352020-09-25 14:01:24
WordPress
hellion35, 2020-09-25 14:01:24

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

Next, I hang the price change function on the woocommerce_before_calculate_totals hook
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);
        }
    }
}

If you go to the cart, everything is fine and works, but the standard woo widget works in my template: WC_Widget_Cart and there is a problem with it, it displays a product with a standard price, but if you change the quantity of goods in this widget, then the desired price is displayed. Please let me know if anyone has experienced something similar? That is, it turns out that this hook is not hung on the woocommerce widget itself. ((((

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pychev Anatoly, 2020-09-25
@hellion35

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 question

Ask a Question

731 491 924 answers to any question