将WooCommerce优惠券代码限制为仅限定义的工作日 [英] Limit a WooCommerce coupon code to defined weekday only

查看:26
本文介绍了将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)如果无效,则显示"Defined Days"优惠券的自定义错误信息:

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+上进行了测试。

这篇关于将WooCommerce优惠券代码限制为仅限定义的工作日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆