I could not find any extensive documentation on the WordPress Heartbeat API, so I am writing here to remember what I have learned through various tutorials throughout the web.
The Heartbeat API is written in Javascript. Think of it like a javascript function that gets run every 60 seconds (depending on the interval) which sends data via POST to the server and then the server returns a response. All of which you can easily hook into. It was introduced in WordPress 3.6.
Quick Examples
PHP
// server received whatever parameters from when javascript triggered the "heartbeat-send" event. function myplugin_heartbeat_received( $response, $data ) { if ( !empty( $data['myplugin_id'] ) ) { $response['myplugin_got_it'] = true; } return $response; } add_filter( 'heartbeat_received', 'myplugin_heartbeat_received', 10, 2 );
Javascript
jQuery(document).ready(function($) { wp.heartbeat.interval= 15; // set some parameters when it's time to send data to the server $(document).on('heartbeat-send.myplugin', function(e, data){ data['myplugin_id'] = my_id; }); // do something when your page gets a response. $(document).on('heartbeat-tick.myplugin', function(e, data){ if ( data.hasOwnProperty( 'myplugin_got_it' ) ) { refreshPage(); } }); });
Heartbeat Pulse Interval
The ‘heartbeat_settings’ filter gets applied in the ‘init’ hook, priority 0 in wp_default_scripts in wp-includes/script-loader.php. So if you do use the hook on the server-side and want to only run it on certain pages, be prepared to parse the URL because a lot of WP functions aren’t available at that time. Alternatively you can set the interval in javascript with wp.heartbeat.interval(15) where 15 is seconds. Note some other tutorials say to use ‘fast’, ‘standard’, ‘slow’, but that didn’t work for me for some reason.
Tutorials
I found these tutorials to be the most helpful.
http://code.tutsplus.com/tutorials/the-heartbeat-api-getting-started–wp-32446
http://code.tutsplus.com/tutorials/the-heartbeat-api-changing-the-pulse–wp-32462
http://code.tutsplus.com/tutorials/heartbeat-api-using-heartbeat-in-a-plugin–wp-32496