3

I have succeed implement this code to remove product from cart with Ajax. But it didn't works with 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 i need to pass $variation_id to $cart_id but i dont know how to do it.

1
  • Also there's error when i try to delete variable product in cart: PHP Warning: call_user_func_array() expects parameter 1 to be a valid callback, no array or string given Commented Sep 2, 2016 at 7:26

1 Answer 1

3

Create the link on cart using the $cart_item_key instead of the $product_id.

Then, on server side, you don't need to use the $cart->generate_cart_id($id); method, because you already have it.

See the example that works for me:

First, the creation of the cart:

// This is the logic that create the cart
foreach ( WC()->cart->get_cart() as $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 the 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']; // This info is already the result of generate_cart_id method now
    /* $cart_id = $cart->generate_cart_id($id); // No need for 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 for me!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.