Search code examples
javascriptphpwordpresswoocommercehook-woocommerce

How to change item price in cart by input field?


In cart.php I have an input where user can input your own price

    <input type="number" id="customPrice">
    <div data-id="<?php echo $product_id ?>" id="updateCart">Update</div>

And I have a js function for make ajax request with product id and new price data

 <script type="text/javascript">
    jQuery(function ($) {
        let customPrice = document.getElementById('customPrice');
        let price = customPrice.value;

        let updateCart = document.getElementById('updateCart');
        let id = updateCart.dataset.id


        updateCart.addEventListener('click', function () {
            $.ajax({
                url: "../wp-admin/admin-ajax.php",
                data: {action: "add_custom_price", id: id, price: 10},
                type: "POST",
                success(data) {
                    if (data) {
                        console.log(data)
                    }
                    $("[name='update_cart']").trigger("click");
                }
            });
        });

    });
</script>

In my functions.php i have

    function add_custom_price($cart)
{
    if (is_admin() && !defined('DOING_AJAX'))
        return;

    if (did_action('woocommerce_before_calculate_totals') >= 2)
        return;

    if (isset($_POST['price']) && $_POST['id']) {
        $price = intval($_POST['price']);
//        $id = intval($_POST['id']);

        foreach ($cart->get_cart() as $cart_item) {
            $cart_item['data']->set_price($price);
        }
    }
}

add_action('wp_ajax_add_custom_price', 'add_custom_price');
add_action('wp_ajax_nopriv_add_custom_price', 'add_custom_price');
add_action('woocommerce_before_calculate_totals', 'add_custom_price', 1000, 1);

But it don't work. I have 500 error

Where is my mistake? Or how i can do it or another way? Any suggestion please


Solution

  • You need to get the product, then affect the price, then save

     function add_custom_price($cart) {
         if (is_admin() && !defined('DOING_AJAX'))
             return;
    
         if (did_action('woocommerce_before_calculate_totals') >= 2)
             return;
    
         if (isset($_POST['price']) && $_POST['id']) {
             $price = intval($_POST['price']);
             $id = intval($_POST['id']);
    
             // Get product
             $product = wc_get_product($id);
             $product->set_regular_price($price);
             $product->save();
             // delete the relevant product transient
             wc_delete_product_transients( $id );
         }
     }