Skip to content
Advertisement

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

I started to work on small Woocommerce project. I have 3 payment gateways into this store: Paypal, Credit Card and Direct bank Transfer.

What I would like is: If coupon code is used, I would like to disable (or remove) Paypal and Credit Card from available payment gateways, and just keep “Direct bank Transfer” as available payment gateway choice.

To show how is look current state from checkout page:

image

I found a similar solution, but this is for removing gateway based on product category.

add_filter( 'woocommerce_available_payment_gateways', 'unset_payment_gateways_by_category' );

function unset_payment_gateways_by_category( $available_gateways ) {
    global $woocommerce;

    $unset = false;
    $category_ids = array( 8, 37 );

    foreach ( $woocommerce->cart->cart_contents as $key => $values ) {
        $terms = get_the_terms( $values['product_id'], 'product_cat' );    
        foreach ( $terms as $term ) {        
            if ( in_array( $term->term_id, $category_ids ) ) {
                $unset = true;
                break;
            }
        }
    }
    if ( $unset == true ) 
        unset( $available_gateways['cheque'] );

    return $available_gateways;
}

So I think that this function can be used, but slightly modified per my problem.

Any help is appreciated.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement