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.
Opens WPIDE on
Code
// 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 add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.