基于时间与日期的WooCommerce加入购物车功能启禁实现问询
Got it, let's solve this exact scenario where you need to enable the add-to-cart button only between 17:00 and 02:00 (next day) from Monday to Sunday, and disable it entirely on Tuesdays. Here's the tailored code snippet you can use:
/** * WooCommerce: Enable/Disable Add-to-Cart Based on Day & Time */ add_filter( 'woocommerce_is_purchasable', 'bbloomer_restrict_add_to_cart_by_day_time', 10, 2 ); add_filter( 'woocommerce_variation_is_purchasable', 'bbloomer_restrict_add_to_cart_by_day_time', 10, 2 ); function bbloomer_restrict_add_to_cart_by_day_time( $purchasable, $product ) { // Get current time in WordPress site's timezone (avoids UTC mismatch) $current_time = current_time( 'timestamp' ); $current_day = date( 'N', $current_time ); // 1 = Monday, 7 = Sunday $current_hour = date( 'H', $current_time ); // Case 1: Tuesday (day 2) - disable add-to-cart entirely if ( $current_day == 2 ) { return false; } // Case 2: Check if current time falls within 17:00 to 02:00 next day $evening_start = strtotime( '17:00', $current_time ); next_day_morning_end = strtotime( '+1 day 02:00', $current_time ); // Handle cross-day time range (evening to midnight + midnight to next day 02:00) if ( ( $current_time >= $evening_start && $current_time <= strtotime( '23:59:59', $current_time ) ) || ( $current_time >= strtotime( '00:00:00', $current_time ) && $current_time <= $next_day_morning_end ) ) { return $purchasable; // Keep add-to-cart enabled } else { return false; // Disable add-to-cart } }
Key Details Explained:
- Timezone Accuracy: Uses
current_time('timestamp')to respect your WordPress site's configured timezone, so you won't run into issues with UTC offsets messing up your schedule. - Tuesday Lockout:
date('N')returns2for Tuesday, so we immediately disable the add-to-cart button for the entire day. - Cross-Day Handling: The code splits the 17:00-02:00 window into two logical parts (evening to midnight, and midnight to early morning) to ensure the restriction works correctly across the day boundary.
- Full Product Support: Targets both simple products (
woocommerce_is_purchasable) and variable products (woocommerce_variation_is_purchasable) to maintain consistency across your store.
How to Implement:
- Add this code to your child theme's
functions.phpfile (always use a child theme to avoid losing changes when your parent theme updates). - If you're not comfortable editing theme files, use a code snippet plugin (like Code Snippets) to safely add the code without touching core theme files.
- Double-check your WordPress timezone settings (under Settings > General) to ensure the time checks align with your local business hours.
内容的提问来源于stack exchange,提问作者maxAndi
相关产品推荐
相关产品推荐

