#Code for rmeove Action
<?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', 'nmh47' ), esc_attr( $product_id ), esc_attr( $_product->get_sku() ), esc_attr( $cart_item_key ) ), $cart_item_key ); ?>
#Remove items from the cart with Ajax
Now, we will add a click event to delete items from the mini cart. You should add this to the main JS file of your theme.
// Ajax delete product from the cart $(document).on('click', '.header-cart-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' );