Last active
April 25, 2016 15:06
-
-
Save dariodev/9d459d95f831ad772f596f1110e5e55c to your computer and use it in GitHub Desktop.
WooCommerce - Removing a product from the cart programatically
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_action( 'template_redirect', 'remove_product_from_cart' ); | |
function remove_product_from_cart() { | |
// Run only in the Cart or Checkout Page | |
if( is_cart() || is_checkout() ) { | |
// Set the product ID to remove | |
$prod_to_remove = 58; | |
// Cycle through each product in the cart | |
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { | |
// Get the Product ID | |
$prod_id = ( isset( $cart_item['variation_id'] ) && $cart_item['variation_id'] != 0 ) ? $cart_item['variation_id'] : $cart_item['product_id']; | |
// Check to see if IDs match and remove it from the cart | |
if( $prod_to_remove == $prod_id ) { | |
$prod_unique_id = WC()->cart->generate_cart_id( $prod_id ); | |
WC()->cart->set_quantity( $cart_item_key, $cart_item['quantity'] - 1, true ); | |
break; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment