wir
6/28/2013 - 9:07 PM

Minimal example demonstrating the WordPress Heartbeat API being added in WP version 3.6.

Minimal example demonstrating the WordPress Heartbeat API being added in WP version 3.6.

<?php
/*
Plugin Name: Heartbeat API Demo
Plugin URI: http://www.strangerstudios.com/wp/heartbeat-api-demo
Description: Minimal example demonstrating the WordPress Heartbeat API being added in WP version 3.6.
Version: .1
Author: strangerstudios

If logged in as a user and viewing the frontend of your website, 
every 15 seconds you should see the following in your Javascript console:

  Client: marco
  Server: polo

*/

/*
	Client-side code. First we enqueue the Heartbeat API and our Javascript. 
	
	Our Javascript is then setup to always send the message 'marco' to the server.
	If a message comes back, the Javascript logs it (polo) to console.
*/

//enqueue heartbeat.js and our Javascript
function hbdemo_init()
{   
	/*
		//Add your conditionals here so this runs on the pages you want, e.g.
		if(is_admin())
			return;			//don't run this in the admin
	*/

    //enqueue the Heartbeat API
    wp_enqueue_script('heartbeat');
    	
    //load our Javascript in the footer
    add_action("wp_footer", "hbdemo_wp_footer");
}
add_action("init", "hbdemo_init");

//our Javascript to send/process from the client side
function hbdemo_wp_footer()
{
?>
<script>
  jQuery(document).ready(function() {				
		//hook into heartbeat-send: client will send the message 'marco' in the 'client' var inside the data array
		jQuery(document).on('heartbeat-send', function(e, data) {
			console.log('Client: marco');
			data['client'] = 'marco';	//need some data to kick off AJAX call
		});
		
		//hook into heartbeat-tick: client looks for a 'server' var in the data array and logs it to console
		jQuery(document).on('heartbeat-tick', function(e, data) {			
			if(data['server'])
				console.log('Server: ' + data['server']);
		});
				
		//hook into heartbeat-error: in case of error, let's log some stuff
		jQuery(document).on('heartbeat-error', function(e, jqXHR, textStatus, error) {
			console.log('BEGIN ERROR');
			console.log(textStatus);
			console.log(error);			
			console.log('END ERROR');			
		});
	});		
</script>
<?php
}

/*
	Our server-side code. 
	
	This hooks into the heartbeat_received filter. 
	It checks for a key 'client' in the data array. If it is set to 'marco', a key 'server' is set to 'polo' in the response array.
*/
function hbdemo_heartbeat_received($response, $data)
{
	if($data['client'] == 'marco')
		$response['server'] = 'polo';
	
	return $response;
}
add_filter('heartbeat_received', 'hbdemo_heartbeat_received', 10, 2);
//add_filter('heartbeat_nopriv_received', 'hbdemo_heartbeat_received', 10, 2);		//uncomment to run for non-users as well