根据 WooCommerce 结帐中显示消息的应用优惠券限制支付网关

问题描述 投票:0回答:1

我只想显示例如如果使用优惠券代码 123,则条纹。因此,我已经提出了有效的代码,但我还想在结账顶部显示一条消息,即显示 woo 通知的地方。 我的消息无法正确显示。

// restrict coupon codes payment method
add_filter('woocommerce_available_payment_gateways', 'unset_gateway_by_applied_coupons');

function unset_gateway_by_applied_coupons($available_gateways) {
    // prevents coupon error in admin
    if( is_admin() ) 
        return $available_gateways;
    
    global $woocommerce;
    $unset = false; // the norm
    
    // names of coupons
    $coupon_codes = array('test123', 'check123');
            
    foreach($coupon_codes as $coupon_code) {
        
        // if code is used in cart
        if(in_array($coupon_code, WC()->cart->get_applied_coupons() )){
            //echo 'found =' .$coupon_code;
            unset($available_gateways['bacs']);
            unset($available_gateways['invoice']);
            // $message = sprintf( __('<br><p class="coupon-code">The coupon code  "%s" can only use the Credit Card payment method.</p>'), $coupon_code);  // <<<<< not working
        }
            
    }
    return $available_gateways;
}
php wordpress woocommerce payment-gateway coupon
1个回答
0
投票

要在有条件地限制某些付款方式时在结账时显示消息,您可以使用

wc_add_notice()
函数,例如:

// Restrict available payment methods based on applied coupons
add_filter('woocommerce_available_payment_gateways', 'restrict_checkout_available_payment_gateways_conditionally');
function restrict_checkout_available_payment_gateways_conditionally( $available_gateways ) {
    // Only on checkout page
    if( is_checkout() && ! is_wc_endpoint_url() ) {
        $targeted_coupons = array('test123', 'check123', 'summer'); // Define here the coupon codes
        $applied_coupons  = WC()->cart->get_applied_coupons();
    
        // Check if any defined coupon code is used in cart
        if( array_intersect($targeted_coupons,$applied_coupons ) ){
            unset($available_gateways['bacs'], $available_gateways['invoice']); 
            // Display message
            wc_clear_notices();
            wc_add_notice( sprintf( __('You can only use the <strong>Credit Card</strong> payment method with coupon %s "%s".'), 
                _n('code', 'codes', count($applied_coupons)), implode( '", "', $applied_coupons) ), 'notice');  
        }
    }
    return $available_gateways;
}

代码位于子主题的functions.php 文件中(或插件中)。已测试并可与 WooCommerce 旧版结账页面短代码配合使用。未经结帐块测试。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.