Limit WooCommerce coupon code to specific day of the week

I would like to restrict coupon code "XYZ" to certain business days, Monday through Thursday. On other days (Monday to Sunday) it will show an error message.

Is it possible? How can I achieve this?

thank

+3


source to share


1 answer


Here is a complete solution with two hook features that restrict coupon usage to specific days of the week and display a custom error notification if the coupon is invalid.

1) Checking the validity of "certain days":

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) Display custom error message for "certain days" coupon if invalid:



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;
}

      

The code goes in the function.php file of your active child theme (or theme), as well as any plugin file.

This working code is tested on WooCommerce 2.6.x and 3.0+ versions.

+5


source







All Articles