user11391182
user11391182

Reputation:

Only show BACS payment gateway for logged in users if a coupon is applied to cart in WooCommerce

The code I have works for hiding the BACS payment gateway for guests and customers, but I need to change it so that the BACS gateway only becomes available IF the customer/admin apply a certain coupon code called FOOD on the CART or CHECKOUT.

In other words: hide the BACS gateway until the COUPON called FOOD is applied on the CART or CHECKOUT.

Here's the code that I have:

add_filter('woocommerce_available_payment_gateways', 'show_bacs_if_coupon_is_used', 99, 1);
function show_bacs_if_coupon_is_used( $available_gateways ) {

        $current_user = wp_get_current_user();

        if ( isset($available_gateways['bacs']) && (current_user_can('customer'))) {
             unset($available_gateways['bacs']);
             } else if ( isset($available_gateways['bacs']) && !is_user_logged_in())  {
             unset($available_gateways['bacs']);
         }
         return $available_gateways;
}

Upvotes: 1

Views: 246

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254363

Only show BACS payment method when a specific coupon is applied to cart for logged in users only (using WC_Cart get_applied_coupons() method):

add_filter('woocommerce_available_payment_gateways', 'show_bacs_for_specific_applied_coupon', 99, 1);
function show_bacs_for_specific_applied_coupon( $available_gateways ) {
    if ( is_admin() ) return $available_gateways; // Only on frontend

    $coupon_code = 'FOOD'; // <== Set here the coupon code

    if ( isset($available_gateways['bacs']) && ! ( is_user_logged_in() &&  
    in_array( strtolower($coupon_code), WC()->cart->get_applied_coupons() ) ) ) {
        unset($available_gateways['bacs']);
    }
    return $available_gateways;
}

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

Upvotes: 1

Related Questions