-
-
Save Firestorm-Graphics/dcb3d86369c4958254678e6f5da233c6 to your computer and use it in GitHub Desktop.
Removing a Product From The Cart Programatically In WooCommerce
This file contains 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 = 56; | |
// Cycle through each product in the cart | |
foreach( WC()->cart->cart_contents as $prod_in_cart ) { | |
// Get the Variation or Product ID | |
$prod_id = ( isset( $prod_in_cart['variation_id'] ) && $prod_in_cart['variation_id'] != 0 ) ? $prod_in_cart['variation_id'] : $prod_in_cart['product_id']; | |
// Check to see if IDs match | |
if( $prod_to_remove == $prod_id ) { | |
// Get it's unique ID within the Cart | |
$prod_unique_id = WC()->cart->generate_cart_id( $prod_id ); | |
// Remove it from the cart by un-setting it | |
unset( WC()->cart->cart_contents[$prod_unique_id] ); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment