# Allow Some Roles to Log In Only During Office Hours

> Lets users in chosen roles, such as shop managers or support staff, log in only on working days between set hours in the site's time zone.

- Type: PHP
- Runs: Run everywhere
- Category: [Login](https://wpide.com/library/category/login/)
- Tags: login, roles, security
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/staff-login-office-hours/

## Code

```php
// Roles limited to office hours, and the hours (24h clock, site time zone).
$wpide_office_roles = array( 'shop_manager', 'editor' );
$wpide_office_start = 8;
$wpide_office_end   = 18;
$wpide_office_days  = array( 1, 2, 3, 4, 5 ); // 1 = Monday ... 7 = Sunday.

$wpide_in_office_hours = function () use ( $wpide_office_start, $wpide_office_end, $wpide_office_days ) {
    $now  = current_datetime();
    $hour = (int) $now->format( 'G' );

    return in_array( (int) $now->format( 'N' ), $wpide_office_days, true ) && $hour >= $wpide_office_start && $hour < $wpide_office_end;
};

$wpide_is_office_user = function ( $user ) use ( $wpide_office_roles ) {
    return $user instanceof WP_User && ! user_can( $user, 'manage_options' ) && array_intersect( $wpide_office_roles, (array) $user->roles );
};

add_filter( 'authenticate', function ( $user ) use ( $wpide_in_office_hours, $wpide_is_office_user ) {
    if ( $wpide_is_office_user( $user ) && ! $wpide_in_office_hours() ) {
        return new WP_Error( 'wpide_office_hours', '<strong>Error:</strong> Your account can only be used during office hours.' );
    }

    return $user;
}, 60 );

add_action( 'init', function () use ( $wpide_in_office_hours, $wpide_is_office_user ) {
    if ( is_user_logged_in() && $wpide_is_office_user( wp_get_current_user() ) && ! $wpide_in_office_hours() ) {
        wp_logout();
    }
} );
```

## Notes

Administrators are never restricted. Staff already logged in are logged out when office hours end.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Allow Some Roles to Log In Only During Office Hours" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
