I'm using woocommerce booking and I need generate coupon restriction for the bookings.
All my bookings have a duration of one hour and the customers can use coupons to reduce the cost of the booking but I need restrict the use of this coupons based in the day when the reservation will be used, not the day when the booking is generated.
For example, I have a coupon and I made my reservation on Mon for a room in Sat, In that case, the coupon must be not good. But if I try to book a room any day of the week for next Monday for example, the coupon must be good.
In this case, I need restrict the use for weekends.
So far my code is:
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 = 'couponyes';
// Set HERE your defined invalid days (others: 'Mon', 'Tue', 'Wed', 'Thu', 'Fri' ) <=== <===
$invalid_days = array( '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;
}
Any idea?
You need a slight different code targeting the booking "start date" when it's submitted on add to cart action. So try this instead:
// Utility function to check coupon code 'abcxxr'
function check_coupon_code( $coupon ){
// Set HERE your coupon slug
$coupon_code_wd = 'abcxxr';
$coupon_code = strtolower($coupon->get_code()); // WC 3.0+
$coupon_code_wd = strtolower($coupon_code_wd);
$found = false;
// Loop through cart items to get the chosen day and check it
foreach( WC()->cart->get_cart() as $cart_item ){
if( $coupon_code_wd == $coupon_code && isset( $cart_item['booking']['_date'] ) ){
$the_day = date('D' , strtotime($cart_item['booking']['_date']));
if( in_array( $the_day, array('Sat', 'Sun') ) ){
$found = true;
}
}
}
return $found;
}
// Coupon validity checking
add_filter( 'woocommerce_coupon_is_valid', 'coupon_week_days_check', 10, 2);
function coupon_week_days_check( $valid, $coupon ) {
if( check_coupon_code( $coupon ) ){
$valid = false;
}
return $valid;
}
// Coupon validity checking error message
add_filter('woocommerce_coupon_error', 'coupon_week_days_error_message', 10, 3);
function coupon_week_days_error_message( $err, $err_code, $coupon ) {
if( intval($err_code) === WC_COUPON::E_WC_COUPON_INVALID_FILTERED && check_coupon_code( $coupon ) ) {
$err = __( "This coupon $coupon_code_wd is valid for week days only…", "woocommerce" );
}
return $err;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.