Using WordPress ‘heartbeat_tick’ PHP action

The heartbeat_tick WordPress PHP action is fired when the Heartbeat ticks in logged-in environments. It allows the transport to be easily replaced with long-polling.

Usage

add_action('heartbeat_tick', 'your_custom_function', 10, 2);
function your_custom_function($response, $screen_id) {
    // your custom code here
    return $response;
}

Parameters

  • $response (array): The Heartbeat response.
  • $screen_id (string): The screen ID.

More information

See WordPress Developer Resources: heartbeat_tick

Examples

Modify Heartbeat interval

Change the Heartbeat interval for a specific screen ID.

add_action('heartbeat_tick', 'modify_heartbeat_interval', 10, 2);
function modify_heartbeat_interval($response, $screen_id) {
    if ($screen_id == 'your_screen_id') {
        $response['heartbeat_interval'] = 60; // Set interval to 60 seconds
    }
    return $response;
}

Add custom data to Heartbeat response

Send custom data with the Heartbeat response.

add_action('heartbeat_tick', 'add_custom_data', 10, 2);
function add_custom_data($response, $screen_id) {
    $response['custom_data'] = 'Your custom data';
    return $response;
}

Notify users when a new post is published

Send a notification to users when a new post is published.

add_action('heartbeat_tick', 'notify_new_post', 10, 2);
function notify_new_post($response, $screen_id) {
    $latest_post_id = get_transient('latest_post_id');
    $current_post_id = get_option('latest_published_post_id', 0);

    if ($latest_post_id > $current_post_id) {
        $response['new_post_id'] = $latest_post_id;
        update_option('latest_published_post_id', $latest_post_id);
    }

    return $response;
}

Monitor logged-in user activity

Track and log user activity by screen ID.

add_action('heartbeat_tick', 'log_user_activity', 10, 2);
function log_user_activity($response, $screen_id) {
    $user_id = get_current_user_id();
    $activity_log = get_option('user_activity_log', array());

    if (!isset($activity_log[$user_id])) {
        $activity_log[$user_id] = array();
    }

    $activity_log[$user_id][$screen_id] = current_time('timestamp');
    update_option('user_activity_log', $activity_log);

    return $response;
}

Check for plugin updates

Periodically check for plugin updates and notify users.

add_action('heartbeat_tick', 'check_plugin_updates', 10, 2);
function check_plugin_updates($response, $screen_id) {
    if ($screen_id == 'plugins') {
        $update_data = get_transient('update_plugins');
        if ($update_data && isset($update_data->response) && count($update_data->response) > 0) {
            $response['plugin_updates'] = count($update_data->response);
        }
    }

    return $response;
}