WooCommerce

WooCommerce – Remove Product in the Cart Widget Using AJAX

WooCommerce – one and the best extensions for building an online store with which I have worked, but like other extensions it is not ideal. In my projects, I tried to make it better and add useful features to make it even more user-friendly. In this article, we’ll talk about how to remove product in the shopping cart widget using AJAX.

First we need to add the attribute data-cart_item_key to the deletion link.

You must change the mini-cart.php template and add the attribute data-cart_item_key to the deletion link


<?php echo apply_filters( 'woocommerce_cart_item_remove_link', sprintf(
    '<a href="%s" class="remove" aria-label="%s" data-product_id="%s" data-product_sku="%s" data-cart_item_key="%s">×</a>',
    esc_url( WC()->cart->get_remove_url( $cart_item_key ) ),
    esc_html__( 'Remove this item', 'deepsoul' ),
    esc_attr( $product_id ),
    esc_attr( $_product->get_sku() ),
    esc_attr( $cart_item_key )
), $cart_item_key ); ?>
If this is not done there will be problems when deleting variable products

Add a click event to the deletion link

Next, we need to add a click event to the product deletion link in the cart. This code should be added to the main JS file of your theme.


// Ajax delete product in the cart
$(document).on('click', '.mini_cart_item a.remove', function (e)
{
    e.preventDefault();

    var product_id = $(this).attr("data-product_id"),
        cart_item_key = $(this).attr("data-cart_item_key"),
        product_container = $(this).parents('.mini_cart_item');

    // Add loader
    product_container.block({
        message: null,
        overlayCSS: {
            cursor: 'none'
        }
    });

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: wc_add_to_cart_params.ajax_url,
        data: {
            action: "product_remove",
            product_id: product_id,
            cart_item_key: cart_item_key
        },
        success: function(response) {
            if ( ! response || response.error )
                return;

            var fragments = response.fragments;

            // Replace fragments
            if ( fragments ) {
                $.each( fragments, function( key, value ) {
                    $( key ).replaceWith( value );
                });
            }
        }
    });
});

Add action to functions.php file to handle AJAX request


// Remove product in the cart using ajax
function warp_ajax_product_remove()
{
    // Get mini cart
    ob_start();

    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item)
    {
        if($cart_item['product_id'] == $_POST['product_id'] && $cart_item_key == $_POST['cart_item_key'] )
        {
            WC()->cart->remove_cart_item($cart_item_key);
        }
    }

    WC()->cart->calculate_totals();
    WC()->cart->maybe_set_cart_cookies();

    woocommerce_mini_cart();

    $mini_cart = ob_get_clean();

    // Fragments and mini cart are returned
    $data = array(
        'fragments' => apply_filters( 'woocommerce_add_to_cart_fragments', array(
                'div.widget_shopping_cart_content' => '<div class="widget_shopping_cart_content">' . $mini_cart . '</div>'
            )
        ),
        'cart_hash' => apply_filters( 'woocommerce_add_to_cart_hash', WC()->cart->get_cart_for_session() ? md5( json_encode( WC()->cart->get_cart_for_session() ) ) : '', WC()->cart->get_cart_for_session() )
    );

    wp_send_json( $data );

    die();
}

add_action( 'wp_ajax_product_remove', 'warp_ajax_product_remove' );
add_action( 'wp_ajax_nopriv_product_remove', 'warp_ajax_product_remove' );

Do you want to see how it works?

Demo

Comments (2)

  • Avatar

    Gantsta

    Thanks so much for this. I’ve spent all morning trying to write this functionality. Your code has proved invaluable!

    Reply

    • Avatar

      alexnet

      I am glad to help 🙂

      Reply

Leave a comment