How to remove product from Woocommerce checkout page using Ajax

To remove a product from the WooCommerce checkout page using AJAX, you’ll need to add some custom code to your theme’s functions.php file. Here’s a step-by-step guide:

  1. Create an AJAX action. This action will be used to remove the product from the cart. Add the following code to your functions.php file:
add_action( 'wp_ajax_remove_product_from_cart', 'remove_product_from_cart' );
add_action( 'wp_ajax_nopriv_remove_product_from_cart', 'remove_product_from_cart' );

function remove_product_from_cart() {
    $product_id = $_POST['product_id'];
    $cart = WC()->instance()->cart;
    $cart_id = $cart->generate_cart_id($product_id);
    $cart_item_id = $cart->find_product_in_cart($cart_id);

    if($cart_item_id){
       $cart->set_quantity($cart_item_id,0);
    }
    wp_die();
}
  1. Add JavaScript to call the AJAX action. You’ll need to add some JavaScript to your theme to call the AJAX action when the user clicks the “Remove” button. You can add this code to your theme’s main JavaScript file, or you can add it directly to your theme’s footer.php file inside <script> tags:
jQuery(document).ready(function($) {
    $('.remove-product').click(function() {
        var product_id = $(this).attr('data-product-id');

        $.ajax({
            type: 'post',
            dataType: 'json',
            url: ajaxurl,
            data: { action: 'remove_product_from_cart', product_id: product_id },
            success: function(response) {
                location.reload();
            }
        });
    });
});
  1. Add the “Remove” button to the checkout page. You’ll need to add a “Remove” button to the checkout page for each product. You can do this by overriding the WooCommerce template file that displays the cart contents on the checkout page. The button should look something like this:
<button class="remove-product" data-product-id="<?php echo $product_id; ?>">Remove</button>

Please replace $product_id with the actual ID of the product.

Please note that this is a basic example and might need to be adjusted based on your specific theme and setup. Always backup your site from your web hosting before making any changes. If you’re not comfortable with these changes, consider hiring a professional developer.

Similar Posts