如果在 WooCommerce 中将优惠券应用于购物车,则仅为登录用户显示 BACS 支付网关

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

我的代码可以为客人和客户隐藏 BACS 支付网关,但我需要更改它,以便 BACS 网关仅在 customer/admin 应用名为 FOOD 的特定优惠券代码时才可用购物车或结帐。

换句话说:隐藏 BACS 网关,直到名为 FOOD 的 COUPON 应用于 CART 或 CHECKOUT。

这是我的代码:

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;
}

仅当特定优惠券应用于登录用户的购物车时才显示 BACS 付款方式 (使用 WC_Cart get_applied_coupons() 方法)

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;
}

代码进入您的活动子主题(或活动主题)的 functions.php 文件。已测试并有效。