WooCommerce: Programmatically Remove Product From Cart Using Product Id.

We Know while adding an item to cart requires just its product ID, removing it from the cart we need to know the “cart item key” .Many Times in WooCommerce we need to remove a product from cart using product ID,if a certain condition is met we follow these steps:-

  1. Generate Cart Id From Product Id
  2. Then Find Product In Cart Using Product Cart Id.
  3. If Product Exist Remove Product From cart.

Example :


function ProgrammaticallyRemoveProductFromCart() {
  if ( is_admin() ) return;
  $product_id = 1234;
  $product_cart_id = WC()->cart->generate_cart_id( $product_id );
  $cart_item_key = WC()->cart->find_product_in_cart( $product_cart_id );
  if ( $cart_item_key ) {
    WC()->cart->remove_cart_item( $cart_item_key );
  }
}
add_action( 'template_redirect', 'ProgrammaticallyRemoveProductFromCart' );

This Function is used when the page reload,but in some case we need to remove it using the ajax .
No need to worry about it, it’s same process like the previous ,the only difference is previously we used it in template_redirect hook,but now we use it in ajax function.


function ProgrammaticallyRemoveProductFromCart() {
  $product_id = $_POST['product_id'];
  $product_cart_id = WC()->cart->generate_cart_id( $product_id );
  $cart_item_key = WC()->cart->find_product_in_cart( $product_cart_id );
  if ( $cart_item_key ) {
    WC()->cart->remove_cart_item( $cart_item_key );
    return true;
  }
  return false;
}
add_action('wp_ajax_remove_item_from_cart', 'ProgrammaticallyRemoveProductFromCart');
add_action('wp_ajax_nopriv_remove_item_from_cart', 'ProgrammaticallyRemoveProductFromCart');

Script:

$.ajax({
  type: "POST",
  url: '#site url#/wp-admin/admin-ajax.php',
  data: {action : 'ProgrammaticallyRemoveProductFromCart','product_id' : '1234'},
  success: function (res) {
    if (res) {
      alert('Removed Successfully');
    }
  }
});

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top