Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Minimal example demonstrating the WordPress Heartbeat API being added in WP version 3.6.
Plugin Name: Heartbeat API Demo
Plugin URI:
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.
return; //don't run this in the admin
//enqueue the Heartbeat API
//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()
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) {
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('END ERROR');
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

This comment has been minimized.

Copy link

@TBAIKamine TBAIKamine commented Oct 15, 2020

this BS doesn't work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment