As part of the JavaScript chapter for our upcoming book Building Web Apps with WordPress, I got a chance to research and work with the Heartbeat API that is new to WordPress 3.6.

It’s a cool little piece of functionality that will help out developers building asynchronous apps on top of WordPress.

At first, I didn’t see the need for it. (It’s not too hard for developers to create their own script to poll the server every few seconds.) But I soon realized why an API like this would be useful. If ¬†you have 5 different plugins all with their own server polling, you are going to have 5 different hits to your server every 15 seconds. However, if they all piggyback on the Heartbeat API, those polling requests are going to be bundled so you are only hitting your server 1 time every 15 seconds. There are other benefits, but that’s the big one to me.

For people trying to get started with the Heartbeat API, I put together this nice little minimal example that you can use as a starting point. The script below simply sends the message “marco” from the client and then detects this on the server and sends back “polo”. The messages are logged in the JavaScript console (so if you inspect elements and click on the console tab in Chrome you will see them). You should be able to easily tweak this to send requests like “how many members are logged in?” and send back a number, etc.

Let me know if you have any questions about the API and I’ll try to address them.

9 Responses to “Heartbeat API for WordPress”

  1. Ricard Torres says:

    Nice clean plugin here Jason. I haven’t played with the API but will definitely do after seeing how easy it is.


    • Jason Coleman says:

      Thanks. Look forward to seeing what you and everyone can do with it.

  2. Alex Vorn says:

    Is this possible the server to check every 15 seconds if the client is using the browser with Heartbeat API?

    • Jason Coleman says:

      Hi, Alex. Not sure what you mean in your question, but I’ll try to clear things up. If the site is running 3.6, the Heartbeat API will be available. If you use code like that in the example, it will be enabled on the frontend. The heartbeat is set to run every 15 seconds by default. So as long as you have JS code putting data in there, it will be sent to the server. And the server will get a chance to respond every 15 seconds.

      Do you have a more specific question?

  3. Darren Ethier says:

    I love it when people put up quick looks at some of the new stuff that comes with a new version of WP. Saves me time in getting up to speed on it. Thanks Jason!

    • Jason Coleman says:

      You’re welcome!

  4. Dean says:

    Thanks for this, I’ve been trying to research more about the heartbeat api, not had much luck finding documentation, so this is a nice clear example. Much appreciated!

    • Jason Coleman says:

      No problem. Thanks.

  5. Mathew Porter says:

    Great for integrations for 3.6 users.

* Required
* Required, Private