Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.