Remove some payment gateways if any coupon code is applied in Woocommerce Remove some payment gateways if any coupon code is applied in Woocommerce wordpress wordpress

Remove some payment gateways if any coupon code is applied in Woocommerce


The following code will remove all payment gateways except "Direct bank Transfer" (bacs) only if at least one coupon code has been applied by the customer:

add_filter('woocommerce_available_payment_gateways', 'applied_coupons_hide_payment_gateways', 20, 1 );function applied_coupons_hide_payment_gateways( $available_gateways){    // Not in backend (admin)    if( is_admin() )         return $available_gateways;    // If at least a coupon is applied    if( sizeof( WC()->cart->get_applied_coupons() ) > 0 ){        // Loop through payment gateways        foreach ( $available_gateways as $gateway_id => $gateway ) {            // Remove all payment gateways except BACS (Bank Wire)            if( $gateway_id != 'bacs' )                unset($available_gateways[$gateway_id]);        }    }    return $available_gateways;}

Code goes in function.php file of the active child theme (or active theme). Tested and works.


here you go :

add_filter('woocommerce_available_payment_gateways', 'unset_gatway_by_applied_coupons');function unset_gatway_by_applied_coupons($available_gateways){    $coupons = WC()->cart->applied_coupons;    if (!empty($coupons)) {        unset($available_gateways['bacs']);    }    return $available_gateways;}

what we did here we checked if any coupons is applied trough WC()->cart->applied_coupons; which will return an array of coupons if coupons array not empty remove specific payment gateway

if you want to check if certain coupon is applied and remove gatway based on your condition you can use the following:

add_filter('woocommerce_available_payment_gateways', 'unset_gatway_by_applied_coupons');function unset_gatway_by_applied_coupons($available_gateways){    $coupons = WC()->cart->applied_coupons;    foreach ($coupons as $coupon) {        if ($coupon == 'my_coupon') { //here you can specific your coupon name            unset($available_gateways['bacs']);        }    }    return $available_gateways;}

of course both functions are tested, you just need to place them in your functions.php