For a non profit, I need to create a function that first checks the time and if the time is within range, check what day it is. They only allow purchases on Tuesdays, Thursdays and Saturdays within the given time.
I've tried many things and Time based Enable/Disable Add to Cart in Woocommerce answer has inspired my code below:
function opening_hours() {
date_default_timezone_set('Europe/Paris');
$opening_time = mktime('10', '00', '00', date('m'), date('d'), date('Y'));
$closing_time = mktime('17', '00', '00', date('m'), date('d'), date('Y'));
$now = time();
return ($now >= $opening_time && $now <= $closing_time) ? true : false;
}
add_filter( 'woocommerce_variation_is_purchasable', 'disable_purchases_on_closed_days', 10, 2 );
add_filter( 'woocommerce_is_purchasable', 'disable_purchases_on_closed_days', 10, 2 );
function disable_purchases_on_closed_days( $purchasable, $product ) {
// check if the time is correct for opening hours
if ( opening_hours() ) {
// if the time is right, make sure it is one of the correct days (tuesday, thursday or saturday)
if (date('N') != 2 || date('N') != 4 || date('N') != 6){
// if not the correct day, disable purchase
$purchasable = false;
return $purchasable;
}
}
}
add_action( 'woocommerce_check_cart_items', 'cart_and_checkout_opening_hours' );
add_action( 'woocommerce_checkout_process', 'cart_and_checkout_opening_hours' );
function cart_and_checkout_opening_hours() {
if ( ! opening_hours() ) {
wc_add_notice( __("The online store is currently closed. You can view products, but purchases are not allowed."), 'error' );
}
}
add_action( 'template_redirect', 'shop_is_closed_notice' );
function shop_is_closed_notice(){
if ( ! ( is_cart() || is_checkout() ) && !opening_hours() ) {
$message = esc_html__('The online store is currently closed. You can view products, but purchases are allowed between x-x.', 'woocommerce' );
wc_add_notice( '<span class="shop-closed">' . $message . '</span>', 'notice' );
}
}
But for some reason, I cannot get this to work. I get no errors and no notices and no matter what I do, all products are non purchasable.
Perhaps someone can review the code and give some insight?