php – 仅限WooCommerce优惠券代码到定义的工作日

我想限制优惠券代码“XYZ”仅用于定义的工作日,仅限周一至周四.其他日子(星期五到星期日)会显示错误通知.

可能吗?我怎样才能做到这一点?

谢谢

解决方法:

这是一个完整的解决方案,包含2个挂钩功能,可以限制您定义的工作日的优惠券使用情况,如果优惠券无效,则会显示自定义错误通知.

1)检查“定义天数”优惠券有效期:

add_filter( 'woocommerce_coupon_is_valid', 'coupon_week_days_check', 10, 2);
function coupon_week_days_check( $valid, $coupon ) {

    // Set HERE your coupon slug   <===  <===  <===  <===  <===  <===  <===  <===  <===  <===  
    $coupon_code_wd = 'xyz';
    // Set HERE your defined invalid days (others: 'Mon', 'Tue', 'Wed' and 'Thu')  <===  <===
    $invalid_days = array('Fri', 'Sat', 'Sun');

    $now_day = date ( 'D' ); // Now day in short format

    // WooCommerce version compatibility
    if ( version_compare( WC_VERSION, '3.0', '<' ) ) {
        $coupon_code = strtolower($coupon->code); // Older than 3.0
    } else {
        $coupon_code = strtolower($coupon->get_code()); // 3.0+
    }

    // When 'xyz' is set and if is not a week day we remove coupon and we display a notice
    if( $coupon_code_wd == $coupon_code && in_array($now_day, $invalid_days) ){
        // if not a week day
        $valid = false;
    }
    return $valid;
}

2)如果无效,则显示“已定义天数”优惠券的自定义错误消息:

add_filter('woocommerce_coupon_error', 'coupon_week_days_error_message', 10, 3);
function coupon_week_days_error_message( $err, $err_code, $coupon ) {

    // Set HERE your coupon slug   <===  <===  <===  <===  <===  <===  <===  <===  <===  <===  
    $coupon_code_wd = 'xyz';
    // Set HERE your defined invalid days (others: 'Mon', 'Tue', 'Wed' and 'Thu')  <===  <===
    $invalid_days = array('Fri', 'Sat', 'Sun');

    $now_day = date ( 'D' ); // Now day in short format

    // WooCommerce version compatibility
    if ( version_compare( WC_VERSION, '3.0', '<' ) ) {
        $coupon_code = strtolower($coupon->code); // Older than 3.0
    } else {
        $coupon_code = strtolower($coupon->get_code()); // 3.0+
    }

    if( $coupon_code_wd == $coupon_code && intval($err_code) === WC_COUPON::E_WC_COUPON_INVALID_FILTERED && in_array($now_day, $invalid_days) ) {
        $err = __( "Coupon $coupon_code_wd only works on weekdays and has been removed", "woocommerce" );
    }
    return $err;
}

代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中.

此工作代码在WooCommerce版本2.6.x和3.0上进行了测试.

上一篇:梯度提升树 Gradient Boosting Decision Tree


下一篇:php – 在Woocommerce中添加到购物车之前清空购物车