Learn how to restrict editors’ login in WordPress by time.

Have you ever needed to limit the access time of some users on your WordPress site?

In this tutorial, I’ll show you how to restrict editors’ login (or any other role you want) in WordPress to a specific time, ensuring more security and control over who accesses your site at specific times.

This WordPress function checks if the user trying to log in is an editor and if the current time is between 9:00 AM and 2:00 PM, Monday to Friday. If these conditions are met, the editor is automatically logged out, redirected to the homepage, and the login process is terminated. You can refine this functionality to redirect to a page containing a notice or other content.

In the functions.php file, insert the following function:

/**
 * Checks if the user role is in the restricted roles array and if the current time is between 9am and 2pm, Monday to Friday.
 *
 * @return void
 */
function restrict_login_editor() {
    $current_user = wp_get_current_user();

    if (in_array('editor', (array) $current_user->roles)) {
        $current_time = current_time('H:i');
        $day_of_week = date('N');  // Get the day of the week number (1 for Monday, 2 for Tuesday, etc.)

        // If the current time is between 9am and 2pm and it's a weekday (Monday to Friday)
        if ($current_time >= '09:00' && $current_time <= '14:00' && $day_of_week >= 1 && $day_of_week <= 5) {
            // Log out the editor, redirect to the homepage, and exit the login process
            wp_logout();
            wp_redirect(home_url());
            exit;
        }
    }
}

// Add action to check the time and day of the week at login
add_action('wp_login', 'restrict_login_editor');

With this simple tutorial, you’ve learned how to restrict editors’ login in WordPress based on the current time. This functionality can be useful to ensure that certain users access the site only during the desired hours, increasing security and control over access to your WordPress site.

If you prefer not to use code, there is a plugin that performs the same action: User Blocker.