Buddypress function/code to check if a user is online.
You can use this function to check if a given buddypress user is online.
The function:
Add following code into your functions.php file:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php /** * http://webdeveloperswall.com/buddypress/check-if-a-user-is-online **/ function is_user_online($user_id, $time=5){ global $wp, $wpdb; $user_login = $wpdb->get_var( $wpdb->prepare( " SELECT u.user_login FROM $wpdb->users u JOIN $wpdb->usermeta um ON um.user_id = u.ID WHERE u.ID = $user_id AND um.meta_key = 'last_activity' AND DATE_ADD( um.meta_value, INTERVAL $time MINUTE ) >= UTC_TIMESTAMP() " )); if(isset($user_login) && $user_login !=""){ return true; } else {return false;} } ?> |
Usage :
The function takes a user id as input and return a boolean value of true/false indicating user is online/offline respectively.
A simple use:
|
1 2 3 4 5 6 7 8 |
<?php if(is_user_online(3)){ echo "user id 3 is online"; } else{ echo "user id 3 is offline"; } ?> |
Basically, by default it checks if the said user is active in last 5 minutes or not.
The function takes second optional argument time.
|
1 2 3 4 5 6 7 8 |
<?php if(is_user_online(3, 10)){ echo "user id 3 is active in last 10 minutes"; } else{ echo "user id 3 is inactive since last 10 minutes"; } ?> |
The above code checks if the user is active since last 10 minutes or not.
That’s it in here. Hope you find it helpful.
THX for sharing.
Never seen a beettr post! ICOCBW
Pls I do not understand the useage of $wp and $wpdb pls feel free to send me an email . Also I need codes for comments. Thanks
$wp and $wpdb are global variables available in wordpress. $wp provides abstraction to interact with wordpress core. $wpdb provides abstraction, security etc to communicate with wordpress database.
Amazing tip! Was just scouring the web for that snippet, yours was the only one that worked properly! Thanks!!!!
Hi, this i s a great snippets, but is there a way to check for all users instead of just a user.
this could be a good step to display in member header or member directory if user is online.
I really like your bp message attachment, great plugin.
Thanks
Thnx abbey, nice to hear that you liked the plugin.
Well, you can check if the displayed user is online and show respective message, or online/offline image in member header. Something like:
<?php
global $bp;
if(is_user_online($bp->displayed_user->id)){
echo “<img src=’”.bloginfo(‘stylesheet_directory’).”/images/online.png’ />”;
}
else{
echo “<img src=’”.bloginfo(‘stylesheet_directory’).”/images/offline.png’ />”;
}
?>
makes sense?