Quantcast
Channel:   eSolution Inc   » tutorial
Viewing all articles
Browse latest Browse all 10

Heartbeat API: Using Heartbeat in a Plugin

$
0
0

In this tutorial we’re going to create a simple plugin which uses the Heartbeat API. Our plugin will alert logged in users, via a growl-like notification, whenever another user logs in or out of the site.

Since this tutorial is focussed on the Heartbeat API, I shall leave out details about creating the plugin header or file structure: the plugin is very simple, and you can examine the source code in full at this GitHub repository.

A user will be deemed “logged in” when they log in and have been active within the last 24 hours. If a user logs out or is not active for 24 hours, they’ll be considered to be offline. We’ll keep tabs on the user’s ‘online’ status and ‘last active’ timestamp to help determine who’s currently online.


Logging-in and Logging-out

First we’ll create a couple of functions hooked into code>wp_logincode> and code>wp_logoutcode> hooks. These are triggered when a user logs in/out of WordPress. When a user logs in, we’ll update their log in status (stored as user meta) to ‘true’ and update their last active timestamp.

function whoisonline_logged_in( $username, $user ) {
	update_user_meta( $user->ID, 'whoisonline_is_online', true );
	update_user_meta( $user->ID, 'whoisonline_last_active', time() );
}
add_action( 'wp_login', 'whoisonline_logged_in', 10, 2 );

Similarly, when a user logs out, we’ll update their online status to false:

function whoisonline_logged_out() {
	$user_id = get_current_user_id();
	update_user_meta( $user_id, 'whoisonline_is_online', false );
}
add_action( 'wp_logout', 'whoisonline_logged_out' );

Who’s Online?

Now let’s create a function which returns an array of usernames of active users, indexed by user ID. We’ll use the code>get_users()code> function to query all users who have been active in the last 24 hours (using the code>whoisonline_last_activecode> meta key).

We’ll then discard any users who have logged out by checking the code>whoisonline_is_onlinecode> user / meta data.

function who_is_online( $args = array() ) {

	// Get users active in last 24 hours
	$args = wp_parse_args( $args, array(
		'meta_key' => 'whoisonline_last_active',
		'meta_value' => time() - 24 * 60 * 60,
		'meta_compare' => '>',
		'count_total' => false,
	) );

	$users = get_users( $args );

	// Initiate array
	$online_users = array();

	foreach ( $users as $user ) {
		if ( ! get_user_meta( $user->ID, 'whoisonline_is_online', true ) )
			continue;

		$online_users[$user->ID] = $user->user_login;
	}

	return $online_users;
}

Preparing for the Heartbeat API

Before we deal with the client-side part of the Heaertbeat API, let’s deal with the server’s response to a request for ‘who’s online’. As was covered in part 1 of this series, we’ll hook onto the filter code>heartbeat_receivedcode> (we don’t need to trigger this for logged out users so won’t use the code>heartbeat_nopriv_receivedcode> filter).

First, we’ll update the current user’s activity timestamp, and ensure their status is set to ‘online’. Next we’ll check that a request for ‘who’s online’ data has been made by looking for the code>who-is-onlinecode> key (which we’ll use later) in the received code>$datacode>.

If it has, we’ll respond with an array of logged in users of the form:

array( [User ID] => [User log in] )

As returned by code>who_is_online()code>.

function whoisonline_check_who_is_online( $response, $data, $screen_id ) {

	// Update user's activity
	$user_id = get_current_user_id();
	update_user_meta( $user_id, 'whoisonline_last_active', time() );
	update_user_meta( $user_id, 'whoisonline_is_online', true );

	// Check to see if "who's online?" has been requested
	if ( ! empty( $data['who-is-online'] ) ) {

		// Attach data to be sent
		$response['whoisonline'] = who_is_online();

	}

	return $response;
}
add_filter( 'heartbeat_received', 'whoisonline_check_who_is_online', 10, 3 );
add_filter( 'heartbeat_received', 'whoisonline_check_who_is_online', 10, 3 );

Heartbeat API

Now create the JavaScript file who-is-online.js file in the root of your plugin folder. Below is the outline of the file.

First, we initiate our global variable code>whoisonlinecode>. code>whoisonline.onlinecode> and code>whoisonline.onlinePrevcode> are both ‘associative arrays’ (strictly speaking, in terms of JavaScript, they’re objects) of users logins, indexed by user ID – corresponding to those users who are ‘online’ at the current / previous beat. This is used to determine when a user has logged in or out.

We then initiate our request for data on who’s online with code>wp.heartbeat.enqueuecode> and listen for the response by binding a callback to the event code>heartbeat-tick.whoisonlinecode>. In that callback we check for data returned by the server, perform any necessary actions and then ensure our request for data is queued for the next beat.

// Inititate variables
var whoisonline = { online: false, onlinePrev: false };

jQuery(document).ready(function() {

	//Set initial beat to fast - for demonstrative purposes only!
	wp.heartbeat.interval( 'fast' );

	//Enqueue are data
	wp.heartbeat.enqueue( 'who-is-online', 'whoisonline', false );

	jQuery(document).on( 'heartbeat-tick.whoisonline', function( event, data, textStatus, jqXHR ) {
		if ( data.hasOwnProperty( 'whoisonline' ) ) {
			// Perform actions with returned data
		}

		// In our example, we want to attach data for the next beat.
		// This might not be in the case in all applications: only queue data when you need to.
		wp.heartbeat.enqueue( 'who-is-online', 'whoisonline', false );
	});
});

Now, let’s fill in the details of the logic inside our code>heartbeat-tick.whoisonlinecode> callback. Whenever data is received from the server we first check that it contains an array of logged in users (which would be given by the key ‘whoisonline’), by checking code>data.hasOwnProperty( ‘whoisonline’ )code>. If so…

  • Update code>whoisonline.onlinePrevcode> to reflect who was online at the last beat, and code>whoisonline.onlinecode> to reflect who is online at the current beat.
  • Check for user IDs that appear in code>whoisonline.onlinecode>, but are not in code>whoisonline.onlinePrevcode>. These users have just logged in.
  • Check for user IDs that appear in code>whoisonline.onlinePrevcode>, but are not in code>whoisonline.onlinecode>. These users have just logged out.

The finished JavaScript file then looks like:

var whoisonline = { online: false, onlinePrev: false };

jQuery(document).ready(function() {

	// Set initial beat to fast
	wp.heartbeat.interval( 'fast' );

	// Enqueue are data
	wp.heartbeat.enqueue( 'who-is-online', 'whoisonline', false );

	jQuery(document).on( 'heartbeat-tick.whoisonline', function( event, data, textStatus, jqXHR ) {

		if ( data.hasOwnProperty( 'whoisonline' ) ) {

			if ( whoisonline.online === false ) {
				//If just loaded, don't say anything...
				whoisonline.online = data.whoisonline;
			}
			whoisonline.onlinePrev = whoisonline.online || {};

			for ( var id in whoisonline.onlinePrev ) {
				if ( ! whoisonline.online.hasOwnProperty( id ) ) {
					jQuery.noticeAdd( { text: whoisonline.onlinePrev[id] + " is now offline" } );
				}
			}

			for ( var id in whoisonline.online ) {
				if ( ! whoisonline.onlinePrev.hasOwnProperty( id) ) {
					jQuery.noticeAdd( { text: whoisonline.online[id] + " is now online" } );
				}
			}
		}
		wp.heartbeat.enqueue( 'who-is-online', 'whoisonline', false );
	});
});

Loading Our Scripts and Styles

This plugin will make use of the jQuery Notice add-on by Tim Benniks – a lightweight growl-like notification plugin for jQuery. Simply download it, and extract to the root of your plugin (it should consist of only two files: jquery.notice.js and jquery.notice.css)

Now that the jQuery plugin has been added, the last piece of the puzzle is to enqueue the necessary scripts and styles. We want this plugin to function both on the front-end and admin side, so we’ll use both the code>admin_enqueue_scriptscode> and code>wp_enqueue_scriptscode> hook, but we only want to load the script for logged in users.

function whoisonline_load_scripts() {

	/* Ony load scripts when you need to - in this case, everywhere if the user is logged in */
	if ( is_user_logged_in() ) {
		wp_enqueue_script( 'whoisonline-jquery-notice', plugin_dir_url( __FILE__ ) . 'jquery.notice.js', array( 'jquery' ) );
		wp_enqueue_style( 'whoisonline-jquery-notice', plugin_dir_url( __FILE__ ) . 'jquery.notice.css' );
		wp_enqueue_script( 'whoisonline',  plugin_dir_url( __FILE__ ) . 'who-is-online.js', array( 'heartbeat', 'whoisonline-jquery-notice' ) );
	}
}
add_action( 'admin_enqueue_scripts', 'whoisonline_load_scripts' );
add_action( 'wp_enqueue_scripts', 'whoisonline_load_scripts' );

And that’s the finished plugin.

You can see the code in full at this GitHub repository. There’s plenty of room for improvement here (for instance display a list of users, and when they were last active), but hopefully this relatively simple plugin has demonstrated how the Heartbeat API works.


Other parts in this series:

The Heartbeat API: Changing the Pulse

Source Article from http://feedproxy.google.com/~r/Wptuts/~3/IZIaPwwycbg/


Viewing all articles
Browse latest Browse all 10

Latest Images

Trending Articles





Latest Images