php - Remove variable product from cart with ajax in woocommerce -


i have succeed implement code remove product cart ajax. didn't works variable product.

/**  * remove cart via ajax  */ function product_remove() {     global $wpdb, $woocommerce;     session_start();     $cart = wc()->instance()->cart;     $id = $_post['product_id'];     $cart_id = $cart->generate_cart_id($id);     $cart_item_id = $cart->find_product_in_cart($cart_id);     if($cart_item_id){        $cart->set_quantity($cart_item_id,0);     } } add_action( 'wp_ajax_product_remove', 'product_remove' ); add_action( 'wp_ajax_nopriv_product_remove', 'product_remove' ); 

maybe need pass $variation_id $cart_id dont know how it.

create link on cart using $cart_item_key instead of $product_id.

then, on server side, don't need use $cart->generate_cart_id($id); method, because have it.

see example works me:

first, creation of cart:

// logic create cart foreach ( wc()->cart->get_cart() $cart_item_key => $cart_item ) { ?>     <li class="<?php echo esc_attr( apply_filters( 'woocommerce_mini_cart_item_class', 'mini_cart_item', $cart_item, $cart_item_key ) ); ?>">         // remove product link         <a href="#" onclick="return js_that_call_your_ajax(this);" data-product_id="<?php echo esc_attr( $cart_item_key ); ?>">&times;</a>         // other product info goes here...     </li> <?php } 

now modifications on server-side:

/**  * remove cart via ajax  */ function product_remove() {     global $wpdb, $woocommerce;     session_start();     $cart = wc()->instance()->cart;     $cart_id = $_post['product_id']; // info result of generate_cart_id method     /* $cart_id = $cart->generate_cart_id($id); // no need this! :) */     $cart_item_id = $cart->find_product_in_cart($cart_id);     if($cart_item_id){        $cart->set_quantity($cart_item_id,0);     } } add_action( 'wp_ajax_product_remove', 'product_remove' ); add_action( 'wp_ajax_nopriv_product_remove', 'product_remove' ); 

this works fine me!


Comments