Determine if a User is Online in BuddyPress

Here is a quick function that I wrote to determine whether or not a BuddyPress user is online.

/**
 * Is the current user online
 * 
 * @param $user_id
 *
 * @return bool
 */
function sc_is_user_online( $user_id ) {
    $last_activity = strtotime( bp_get_user_last_activity( $user_id ) );
 
    if ( empty( $last_activity ) ) {
        return false;
    }
 
    // the activity timeframe is 15 minutes
    $activity_timeframe = 15 * MINUTE_IN_SECONDS;
    return ( time() - $last_activity <= $activity_timeframe );
}

The function bp_get_user_last_activity returns the time of the users last activity. Then all we have to do is see if that timestamp falls within the activity timeframe we have established.

That’s it! See I told you it was going to be quick. 🙂

Leave a Reply