Using WordPress ‘heartbeat_send’ PHP filter

The heartbeat_send WordPress PHP filter allows you to modify the Heartbeat API response before it is sent back to the client.

Usage

add_filter('heartbeat_send', 'my_custom_heartbeat_send', 10, 2);

function my_custom_heartbeat_send($response, $screen_id) {
    // your custom code here
    return $response;
}

Parameters

  • $response (array) – The Heartbeat response data.
  • $screen_id (string) – The screen ID for the current page in the admin area.

More information

See WordPress Developer Resources: heartbeat_send

Examples

Add custom data to Heartbeat response

Add custom data to the Heartbeat response to update the client-side.

add_filter('heartbeat_send', 'add_custom_data_to_heartbeat', 10, 2);

function add_custom_data_to_heartbeat($response, $screen_id) {
    $response['my_custom_data'] = 'Hello from server!';
    return $response;
}

Modify the Autosave interval

Change the Autosave interval based on the screen ID.

add_filter('heartbeat_send', 'modify_autosave_interval', 10, 2);

function modify_autosave_interval($response, $screen_id) {
    if ('post' === $screen_id) {
        $response['heartbeat_interval'] = 120; // Autosave every 120 seconds
    }
    return $response;
}

Send a notification when a new post is published

Send a notification to the client when a new post is published.

add_filter('heartbeat_send', 'send_new_post_notification', 10, 2);

function send_new_post_notification($response, $screen_id) {
    $last_published = get_transient('last_published_post');
    if (false !== $last_published) {
        $response['new_post_notification'] = $last_published;
        delete_transient('last_published_post');
    }
    return $response;
}

Refresh nonces

Refresh nonces for forms on the current screen.

add_filter('heartbeat_send', 'refresh_nonces', 10, 2);

function refresh_nonces($response, $screen_id) {
    if ('post' === $screen_id) {
        $response['new_nonce'] = wp_create_nonce('my_custom_nonce');
    }
    return $response;
}

Send logged-in user count

Send the number of logged-in users to the client.

add_filter('heartbeat_send', 'send_logged_in_user_count', 10, 2);

function send_logged_in_user_count($response, $screen_id) {
    $user_count = count_users();
    $response['logged_in_users'] = $user_count['total_users'];
    return $response;
}