PHP Function to redirect based on time and day

49 Views Asked by At

I have a WP restaurant site that has a lunch menu and a dinner menu. They are /lunch-menu/ and /dinner-menu/ respectively. I also have a page called /menu/ that is designed to redirect the user to the correct menu page based on time/day.

The lunch menu is available Monday - Friday from 11am - 3pm. So, I check the day:

function is_weekday() {
    $day_of_week = date('N'); // 1 (for Monday) through 7 (for Sunday)
    return ($day_of_week >= 1 && $day_of_week <= 5);
}

then check the time

// Function to check if the current time in Central Time Zone is before 3 PM
function is_before_3pm() {
    $timezone = 'America/Chicago'; // Central Time Zone
    $current_time = new DateTime(null, new DateTimeZone($timezone));
    $time_3pm = new DateTime('3:00 PM', new DateTimeZone($timezone));

    return $current_time < $time_3pm;
}

then redirect any non-admin users

// Redirect users who are not logged in as admin based on current day and time in Central Time Zone
add_action('template_redirect', 'menu_redirect');

function menu_redirect() {
    // Check if the user is not logged in as admin
    if (!current_user_can('activate_plugins')) { // Change the capability to the appropriate admin capability if needed.
        // Check if the current URL contains '/menu/'
        if (strpos($_SERVER['REQUEST_URI'], '/menu/') !== false) {
            // Check if it's a weekday and before 3 PM in Central Time Zone
            if (is_weekday() && is_before_3pm()) {
                wp_redirect('/lunch-menu/');
                exit;
            } else {
                wp_redirect('/dinner-menu/');
                exit;
            }
        }
    }
}

This works great. But, I am having an issue when using a link pointing directly to /lunch-menu/ or /dinner-menu/. The user is getting redirected. It doesn't happen if I type one of those URLs directly into my browser. Only if I add a link to an element that should point to one of them specifically.

I'm using WordPress and Elementor. And I tried setting the link on the element to both the internal -> content -> lunch-menu and putting the entire hard-coded link in. Same behavior in both cases.

Can anyone tell me why? It would be much appreciated!

0

There are 0 best solutions below