Seperate session limit for desktop and mobile devices

Thanks to the handy filters and actions it is easily possible to set seperate limits for mobile and desktop devices. For this snippet you should use the "session_limit" filter.

add_filter("session_limit", "limit_modification", 99, 2);
function limit_modification(int $limit, WP_User $user) {

    $mobile_limit = 1;
    $desktop_limit = 3;

    // Handle logged in users
    if (is_user_logged_in()) {

        $manager = new \JUVO_SessionManager\User_Sessions($user);

        // Get current session to determin if mobile or desktop limit is in scope
        $currentSessionVerifier = $manager->get_session_verifier(wp_get_session_token());
        $currentSession = $manager->get_session($currentSessionVerifier);

        if ($currentSession->getUserAgent()->isMobile()) {
            // Mobile
            return $mobile_limit;
        } else {
            // Desktop
            return $desktop_limit;
        }
    }

    // Get session info of unauthenticated user
    $ua_parser = new WhichBrowser\Parser($_SERVER['HTTP_USER_AGENT']);

    if ($ua_parser->isMobile()) {
        // Mobile
        return $mobile_limit;
    } else {
        // Desktop
        return $desktop_limit;
    }

}

Explaination of this snippet

Logged in users

  1. Instantiate User_Sessions class to work with the sessions of the authenticated user
  2. Get current session
    1. Get current session token
    2. Get session verifier by session token
    3. Get session by verifier
  3. Check if user agent of current session is a mobile one
  4. Return either mobile or desktop limit set in variable at the top

Unauthenticated users

  1. Instantiate WhichBrowser\Parser to identify current user agent.
  2. Check if user agent of current session is a mobile one
  3. Return either mobile or desktop limit set in variable at the top