Voxfor - All rights reserved - 2013-2025
We Accepted





The WordPress Heartbeat API is a powerful tool that enables real-time communication between a user’s browser and the server. By leveraging this API, developers can create dynamic, auto-updating dashboard widgets that display live data—such as website traffic, server health, or e-commerce sales—without requiring manual page refreshes. This guide provides a detailed process of creating a plugin that interacts with the Heartbeat API to deliver real-time updates, ensuring you understand not just the “how” but also the “why” behind each step.
The Heartbeat API is a WordPress core feature that facilitates real-time updates by sending periodic AJAX requests (or “pulses”) to the server. By default, it runs on post-editing screens and the dashboard, sending data to the server and receiving responses at regular intervals.
Before diving into code, create a dedicated plugin to keep your functionality isolated and manageable.
Inside the folder, create live-dashboard-widget.php with the following header:
// PHP Code
<?php
/**
* Plugin Name: Live Dashboard Widget
* Description: Displays real-time updates using the WordPress Heartbeat API.
* Version: 1.0
* Author: Your Name
*/
Most admin pages disable the Heartbeat API by default. You must explicitly enqueue it to use it on the dashboard.
Insert the following code into your plugin file:
// PHP Code
add_action('admin_enqueue_scripts', 'enable_heartbeat_on_dashboard');
function enable_heartbeat_on_dashboard($hook) {
// Load only on the dashboard
if ($hook !== 'index.php') {
return;
}
// Enqueue the Heartbeat API
wp_enqueue_script('heartbeat');
// Add custom JavaScript
wp_enqueue_script(
'live-dashboard-script',
plugins_url('js/live-dashboard.js', __FILE__),
array('heartbeat', 'jquery'), // Dependencies
'1.0',
true // Load in footer
);
// Pass data to JavaScript (e.g., security nonce)
wp_localize_script('live-dashboard-script', 'liveDashboard', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('live_dashboard_nonce')
));
}
Explanation
Create a JavaScript file (js/live-dashboard.js) to manage data sending and receiving.
// Javascript
jQuery(document).ready(function ($) {
// Listen for data sent back from the server
$(document).on('heartbeat-tick', function (e, data) {
if (data.live_dashboard) {
updateDashboardWidget(data.live_dashboard);
}
});
// Send custom data to the server with each heartbeat
$(document).on('heartbeat-send', function (e, data) {
data.live_dashboard = {
action: 'get_stats',
nonce: liveDashboard.nonce
};
});
});
// Update the widget's HTML with new data
function updateDashboardWidget(stats) {
const widgetContent = `
<div class="live-stats">
<h3>Real-Time Stats</h3>
<ul>
<li>Visitors Now: ${stats.visitors}</li>
<li>Sales Today: ${stats.sales}</li>
<li>Server Load: ${stats.server_load}%</li>
</ul>
</div>
`;
$('#live_dashboard_widget .inside').html(widgetContent);
}
Explanation
Process incoming requests and return data using the heartbeat_received filter.
// PHP Code
add_filter('heartbeat_received', 'handle_heartbeat_request', 10, 3);
function handle_heartbeat_request($response, $data, $screen_id) {
// Security check: Verify nonce
if (
!isset($data['live_dashboard']['nonce']) ||
!wp_verify_nonce($data['live_dashboard']['nonce'], 'live_dashboard_nonce')
) {
return $response;
}
// Process the request
if (isset($data['live_dashboard']['action']) && $data['live_dashboard']['action'] === 'get_stats') {
$response['live_dashboard'] = array(
'visitors' => get_live_visitor_count(),
'sales' => get_todays_sales(),
'server_load' => get_server_load()
);
}
return $response;
}
// Example data-fetching functions (customize these)
function get_live_visitor_count() {
// Replace with actual analytics integration
return rand(50, 200);
}
function get_todays_sales() {
// Replace with e-commerce platform API call
return rand(10, 50);
}
function get_server_load() {
// Replace with server monitoring logic
return rand(1, 100);
}
Explanation
Register a custom widget to display the data.
// PHP Code
add_action('wp_dashboard_setup', 'register_live_dashboard_widget');
function register_live_dashboard_widget() {
wp_add_dashboard_widget(
'live_dashboard_widget', // Widget ID
'Live Site Stats', // Widget title
'render_dashboard_widget', // Callback function
'dashboard_widget_control' // Optional control callback (not used here)
);
}
function render_dashboard_widget() {
// Initial content (loading state)
echo '<div class="live-stats"><p>Loading real-time data...</p></div>';
}
Explanation
Reduce server load by slowing the pulse interval:
// PHP Code
add_filter('heartbeat_settings', 'adjust_heartbeat_frequency');
function adjust_heartbeat_frequency($settings) {
$settings['interval'] = 60; // 60 seconds between beats
return $settings;
}
if (!current_user_can('manage_options')) {
return $response;
}
Push alerts when new events occur:
// In handle_heartbeat_request()
$new_orders = get_new_orders_since_last_check();
if (!empty($new_orders)) {
$response['live_dashboard']['notifications'] = $new_orders;
}
Use Chart.js to render graphs:
// Javascript
function updateDashboardWidget(stats) {
const canvas = '<canvas id="trafficChart" width="400" height="200"></canvas>';
$('#live_dashboard_widget .inside').html(canvas);
// Initialize chart with stats.historical_data
}
Tailor responses to the current user:
// PHP Code
$user_id = get_current_user_id();
$response['live_dashboard']['user_data'] = get_user_activity($user_id);
Alternatives include WebSockets for real-time communication or Server-Sent Events (SSE). These methods require more setup but can provide more robust solutions for high-frequency data updates.
The WordPress Heartbeat API is a versatile tool that allows developers to create dynamic, real-time features within the WordPress admin area. By following these guidelines, you can build a live dashboard widget that fetches and displays data securely and efficiently.
Final Tips:
With these techniques, you can enhance the functionality of your WordPress site, providing users with valuable real-time insights and improving their overall experience.
Hassan Tahir wrote this article, drawing on his experience to clarify WordPress concepts and enhance developer understanding. Through his work, he aims to help both beginners and professionals refine their skills and tackle WordPress projects with greater confidence.