我只想显示例如如果使用优惠券代码 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;
}
要在有条件地限制某些付款方式时在结账时显示一条消息,您可以使用 WooCommerce
wc_add_notice()
功能。
此外,您的代码不处理 WooCommerce“订单付款”。
以下将根据结帐页面和订单支付页面中应用的优惠券限制可用的付款方式,并显示一条消息:
// 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 ) {
$targeted_coupons = array('test123', 'check123'); // Define here the coupon codes
// Only on checkout and order pay
if( is_checkout() ) {
if ( is_wc_endpoint_url('order-pay') ) { // Order pay page
global $wp;
$order_id = absint( $wp->query_vars['order-pay'] );
$order = wc_get_order($order_id);
$applied_coupons = $order->get_coupon_codes();
} elseif ( ! is_wc_endpoint_url() ) { // Checkout page
$applied_coupons = WC()->cart->get_applied_coupons();
}
// Check if any defined coupon code is used in cart
if ( $applied_coupons && array_intersect($targeted_coupons, $applied_coupons ) ) {
if ( isset($available_gateways['bacs']) ) {
unset($available_gateways['bacs']);
}
if ( isset($available_gateways['invoice']) ) {
unset($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 旧版结账页面短代码配合使用。未经结帐块测试。也在“订单支付”页面进行了测试。