Home » Code Examples » Seperate session limit for desktop and mobile devices

March 26, 2021

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

How to add this code snippet?

We recommend that you add the code snippets to your themes functions.php file. Make sure you create backups before you add any customization. Please make sure that you always have a plan ready if a code snippet causes errors. Detailed information about how to add code snippets to your WordPress installation can be found here: wpbeginner.com

Need help customizing session manager?

You are looking for a custom solution, to make the session manager truly fit your needs? No problem we got you covered. Simply send us a short briefing about your requirements and we send you a quote if there is not already a solution. If your problem requires changes on the plugin and we think the new functionality might be a feature many users would like, we implement it in the core of our plugin. This way you profit from features others requested and also be an awesome part of the community.

Leave a Reply

Your email address will not be published. Required fields are marked *