The WordPress Heartbeat API is pretty new so there isn’t much out there for it yet. I recently had a need for it – and realized that all the examples are pretty complex for a basic introduction. So here’s an extremely simplified breakdown:

The first thing we need to do is enqueue the javascript. If you’ve ever used javascript in WordPress before, this function is straightforward. (If not, head over to the WordPress codex to learn more about enqueueing)

function heartbeat_test_enqueue($hook_suffix) {

        // Make sure the JS part of the Heartbeat API is loaded.
        wp_enqueue_script('heartbeat');

        // Output the test JS in admin footer.
        add_action( 'admin_print_footer_scripts', 'heartbeat_test_js', 20 );

}
add_action( 'admin_enqueue_scripts', 'heartbeat_test_enqueue' );

Next, we’ll demonstrate the ‘heartbeat’ by creating an “alert” popup when the heartbeat “ticks” – which is every minute.

function heartbeat_test_js() {
        ?>
        <script>

        jQuery(document).ready( function($) {

                // Listen for the custom event "heartbeat-tick" on $(document). This fire's once every minute that the page is open.
                $(document).on( 'heartbeat-tick', function(e, data) {

                            alert("1 Minute Has Passed");

                });
      });

      </script>
       <?php
}

Put those two functions in a plugin or your functions.php file and it will alert you everytime a minute has gone by.

Where to go from here

This is only an extremely basic example of how the heartbeat works and what it can do. To learn more about how you can update PHP scripts on heartbeat ticks and modify other information, check out these links which go into further detail:

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.