I have added a function to add a free product when a certain coupon code is entered.
I now need to check if the original product is still in the cart, and if not, remove coupon and free product from the cart.
add_action('woocommerce_applied_coupon', 'apply_product_on_coupon');
function apply_product_on_coupon( ) {
global $woocommerce;
$coupon_idcus = 'ccam0620';
$free_product_id = 11259;
if(in_array($coupon_idcus, $woocommerce->cart->get_applied_coupons())){
$woocommerce->cart->add_to_cart($free_product_id, 2);
}
}
You will need another action to check if the coupon was removed.
function action_woocommerce_removed_coupon( $coupon_code ) {
if($coupon_code == 'ccam0620') {
$product_id = 11259;
$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 the action
add_action( 'woocommerce_removed_coupon', 'action_woocommerce_removed_coupon', 10, 1 );
This should do it - I haven't tested it.
Source 1: http://hookr.io/actions/woocommerce_removed_coupon/
Source 2: https://businessbloomer.com/woocommerce-remove-product-from-cart-programmatically/