Using WordPress ‘heartbeat_nopriv_tick’ PHP action

The heartbeat_nopriv_tick WordPress action fires when the Heartbeat ticks in no-privilege environments, allowing the transport to be easily replaced with long-polling.

Usage

add_action('heartbeat_nopriv_tick', 'your_custom_function', 10, 2);

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

Parameters

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

More information

See WordPress Developer Resources: heartbeat_nopriv_tick

Examples

Modify response for a specific screen ID

Modify the Heartbeat response for a specific screen ID in no-privilege environments.

add_action('heartbeat_nopriv_tick', 'modify_heartbeat_response', 10, 2);

function modify_heartbeat_response($response, $screen_id) {
    if ($screen_id == 'my_screen_id') {
        // Modify the response for 'my_screen_id'
        $response['my_key'] = 'my_value';
    }
    return $response;
}

Add custom data to the Heartbeat response

Add custom data to the Heartbeat response in no-privilege environments.

add_action('heartbeat_nopriv_tick', 'add_custom_data', 10, 2);

function add_custom_data($response, $screen_id) {
    // Add custom data to the Heartbeat response
    $response['custom_data'] = 'Your custom data';
    return $response;
}

Log Heartbeat ticks for no-privilege environments

Log Heartbeat ticks for no-privilege environments.

add_action('heartbeat_nopriv_tick', 'log_heartbeat_ticks', 10, 2);

function log_heartbeat_ticks($response, $screen_id) {
    // Log Heartbeat ticks to a file
    file_put_contents('heartbeat_ticks.log', "Screen ID: $screen_id - " . date('Y-m-d H:i:s') . "\n", FILE_APPEND);
    return $response;
}

Clear cache on Heartbeat tick

Clear cache for a specific screen ID on Heartbeat tick in no-privilege environments.

add_action('heartbeat_nopriv_tick', 'clear_cache_on_tick', 10, 2);

function clear_cache_on_tick($response, $screen_id) {
    if ($screen_id == 'my_screen_id') {
        // Clear cache for 'my_screen_id'
        wp_cache_delete('my_cache_key');
    }
    return $response;
}

Send notifications on Heartbeat tick

Send notifications to users on Heartbeat tick in no-privilege environments.

add_action('heartbeat_nopriv_tick', 'send_notifications', 10, 2);

function send_notifications($response, $screen_id) {
    // Send notifications to users
    // Replace with your custom notification logic
    your_custom_notification_function();
    return $response;
}