Andy Tran

Create Custom Dashboard Widget for Active Users

by | 13 Sep, 2021 | Wordpress | 0 comments

custom widget for active users

Why Active Users count is important ?

From a business perspective, active users are important because they generate revenue. A good website needs active users to survive, so a healthy count of active users is a positive sign of success. Calculating the number of active users on the website over a period of time can help assess the effectiveness of the campaign.

There are many options to display the active users in the word-press. Like, You can use the word-press plugin or you can develop your own custom functions to see the active users count on the dashboard.

Here we are going to discuss and learn how to create a custom dashboard widget on WordPress. For this, you can write a custom function in the functions.php file or you can develop a separate plugin separately. Here we are going to develop a custom plugin to display active user count on Dashboard.

If you do not read our blog for ‘how to create custom Plugin in word-press’, please explore it here Create Own Coupon Custom Plugin .

What we are going to do:

  • We will create a custom Dashboard Widget for Active Users, Firstly
    • Go the Website Folder -> wp-content -> plugins -> create Folder (users)
    • In that Folder,
      • Create users.php file for the Plugin Code.
      • Create readme.txt file for basic Information.
        • Plugin Metadata
        • Description
        • Installation Steps
        • FAQ section
        • Screenshots
        • Change log
      • Create a .css file if you want to add any additional CSS.
  • Plugin will have below functionality.
    • Display Total Count of the Currently active user’s Name and Email ID.
    • Display Total Count of the Registered Users.

Knowing when your WordPress users are currently active is really helpful whether you open sign-ups to the public, or if you have a private site with multiple users. We are now adding a custom Dashboard widget to display the current users count as well as currently active users on the site.

WordPress Transients

we are using a transient to store a temporary array of user login data so that we can get the user’s data. They will save lots of queries on your database by temporarily storing data in a cache for a certain amount of time. If they don’t exist or have expired, they will simply return false. To learn more about how and when to use WordPress transients, please explore the linked content,

To store the current user’s data, we need to create the transient that is updated whenever a user becomes active.
We should check the transient to see if the user exists or if they have not been online in the last 5 minutes.

If they need to be updated, we should update the transient array by appending to it with their ID as the index. In that array we should store their ID, User Name, User Email Address & Last Access Time.

Active User Count in WordPress Dashboard Metabox

To create a custom meta box for the WordPress Dashboard to display how many users are currently on the site, We should use the hook into the wp_dashboard_setup action to register our custom meta box. And to add the widget we should be using wp_add_dashboard_widget that hooks.

Currently Active Users Count

To get an integer of who is currently active, we just need to loop through the transient array, and if that index’s last active time is within the last 5 minutes increment a counter. Then we’ll return that count at the end. So you could also get a list and Total Count of who is currently active on the site.

Write below code users.php plugin File


<?php
/*
Plugin Name: Users Info
Description: Plugin for logged in users info
Version: 1.0.0
Author: PALAK
*/

//Active Users Metabox
add_action('wp_dashboard_setup', 'activeusers_metabox');
function activeusers_metabox(){
	global $wp_meta_boxes;
	wp_add_dashboard_widget('activeusers', 'Active Users', 'dashboard_activeusers');
}
function dashboard_activeusers(){
		$user_count = count_users();
		$users_plural = ( $user_count['total_users'] == 1 )? 'User' : 'Users'; //Determine singular/plural tense
		echo '<div><a href="users.php">' . $user_count['total_users'] . ' ' . $users_plural . '</a> 
		      <small> (' . online_users('count') . ' currently active) </small>
			  </div><br>';
		//print_r(online_name('name'));
		echo "<strong>Active User's List</strong><br>";
		$i=1;
		foreach(online_name('name') as $key => $value) {
			echo "$i) ${value['username']}  ${value['useremail']}" . "<br>";
			$i++;
		}	  
}

//Get a count of online users, or an array of online user IDs.
//Pass 'count' (or nothing) as the parameter to return a count, otherwise it will return an array of online user data.
function online_users($return='count'){
	$logged_in_users = get_transient('users_status');
	
	//If no users are online
	if ( empty($logged_in_users) ){
		return ( $return == 'count' )? 0 : false; //If requesting a count return 0, if requesting user data return false.
	}
	
	$user_online_count = 0;
	$online_users = array();
	foreach ( $logged_in_users as $user ){
		if ( !empty($user['username']) && isset($user['last']) && $user['last'] > time()-300 ){ //If the user has been online in the last 300 seconds, add them to the array and increase the active count.
			$online_users[] = $user;
			$user_online_count++;
		}
	}

	return ( $return == 'count' )? $user_online_count : $online_users; //Return either an integer count, or an array of all active user data.
}

//To get Active Users name
function online_name($return='name'){
	$logged_in_users = get_transient('users_status');
	
	//If no users are active
	if ( empty($logged_in_users) ){
		return ( $return == 'name' )? 0 : false; //If you're looking for a count, return 0; if you're looking for user data, return false.
	}
	
	//$user_online_count = 0;
	$online_users = array();
	foreach ( $logged_in_users as $user ){
		if ( !empty($user['username']) && isset($user['last']) && $user['last'] > time()-300 ){ //Add the user to the array and increase the active count if they have been online in the last 300 seconds.
			$online_users[] = $user;
		}
	}

	return ( $return == $online_users )? $user_online_count : $online_users; //Return an integer count or an array containing all active user data.
}

//Update user active status
add_action('init', 'users_status_init');
add_action('admin_init', 'users_status_init');
function users_status_init(){
	$logged_in_users = get_transient('users_status'); //Get the active users from the transient.
	$user = wp_get_current_user(); //Get the current user's data

	//Update the user if they are not on the list, or if they have not been online in the last 300 seconds (5 minutes)
	if ( !isset($logged_in_users[$user->ID]['last']) || $logged_in_users[$user->ID]['last'] <= time()-300 ){
		$logged_in_users[$user->ID] = array(
			'id' => $user->ID,
			'username' => $user->user_login,
			'useremail' => $user->user_email,
			'last' => time(),
		);
		set_transient('users_status', $logged_in_users, 300); //Set this transient to expire 5 minutes after it is created.
	}
}

//Check if a user has been active in the last 5 minutes
function is_user_online($id){	
	$logged_in_users = get_transient('users_status'); ///from the transient, get the active users.
	
	return isset($logged_in_users[$id]['last']) && $logged_in_users[$id]['last'] > time()-300; //Return boolean if the user has been online in the last 300 seconds (5 minutes).
}

//Check when a user was last online.
function user_last_online($id){
	$logged_in_users = get_transient('users_status'); //retrieve the active users from the transients.
	
	//Determine if the user has ever been logged in (and return their last active date if so).
	if ( isset($logged_in_users[$id]['last']) ){
		return $logged_in_users[$id]['last'];
	} else {
		return false;
	}
}
?>

After activating the plugin, Go to Dashboard & you should display the Custom Dashboard Widget of Currently Active Users.
display custom dashboard widget for currently active users

Here, you can display a Total of 10 Numbers of Registered Users and One User is Currently Active on the site. You also display the list of all current user’s Names and Email Addresses.

Need top-notch IT consulting and services? Look no further than Erudite Works Pvt. Ltd. We excel in salesforce consulting, mobile app & web development, offering innovative solutions trusted by millions.

Also Read : Our Blog Post On: Add Sub Menu in Custom Post Type

Share this article...

0 Comments

Submit a Comment

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


The reCAPTCHA verification period has expired. Please reload the page.