在WooCommerce结帐前强制优惠券代码

问题描述

我想强迫客户添加优惠券代码,然后他们才能结帐。我希望它可以与WooCommerce商店中的每个优惠券代码和每个产品一起使用。

我正在使用此代码,它几乎可以解决问题,但仅适用于单个优惠券代码(freev1

如何使其在生成的每个优惠券代码上都能正常工作?

add_action( 'woocommerce_check_cart_items','mandatory_coupon_code' );
function mandatory_coupon_code() {
    // HERE set your coupon code
    $mandatory_coupon = 'freev1';

    $applied_coupons = WC()->cart->get_applied_coupons();

    // If coupon is found we exit
    if( in_array( $mandatory_coupon,$applied_coupons ) ) return;

    // Not found: display an error notice
    wc_add_notice( __( 'Add coupon before checkout.','woocommerce' ),'error' );
}

解决方法

只需检查$applied_coupons是否为空,添加空通知即可。删除$mandatory_couponif ( in_array...

所以你得到

function mandatory_coupon_code() {
    $applied_coupons = WC()->cart->get_applied_coupons();

    if ( empty ( $applied_coupons ) ) {
        // Not found: display an error notice
        wc_add_notice( __( 'Add coupon before checkout.','woocommerce' ),'error' );   
    }
}
add_action( 'woocommerce_check_cart_items','mandatory_coupon_code',10,0 );

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...