插件开发文档

💡 云策文档标注

概述

Heartbeat API 是 WordPress 内置的服务器轮询 API,用于实现近实时的前端更新。它通过客户端定时发送数据到服务器,并在服务器端处理后返回响应,支持自定义事件处理。

关键要点

  • Heartbeat API 基于客户端定时“tick”机制,每 15-120 秒发送数据到服务器,并通过 admin-ajax 处理响应。
  • 自定义事件涉及三个步骤:在 JavaScript 中添加发送数据(heartbeat-send 事件)、在 PHP 中处理数据并返回响应(heartbeat_received 过滤器)、在 JavaScript 中处理返回数据(heartbeat-tick 事件)。
  • 开发者可以根据需求选择使用部分步骤,例如仅处理接收和响应,无需发送数据。

代码示例

// 发送数据到服务器
jQuery( document ).on( 'heartbeat-send', function ( event, data ) {
    data.myplugin_customfield = 'some_data';
});

// 服务器端接收和响应
function myplugin_receive_heartbeat( array $response, array $data ) {
    if ( empty( $data['myplugin_customfield'] ) ) {
        return $response;
    }
    $received_data = $data['myplugin_customfield'];
    $response['myplugin_customfield_hashed'] = sha1( $received_data );
    return $response;
}
add_filter( 'heartbeat_received', 'myplugin_receive_heartbeat', 10, 2 );

// 处理响应
jQuery( document ).on( 'heartbeat-tick', function ( event, data ) {
    if ( ! data.myplugin_customfield_hashed ) {
        return;
    }
    alert( 'The hash is ' + data.myplugin_customfield_hashed );
});

📄 原文内容

The Heartbeat API is a simple server polling API built in to WordPress, allowing near-real-time frontend updates.

How it works

When the page loads, the client-side heartbeat code sets up an interval (called the “tick”) to run every 15-120 seconds. When it runs, heartbeat gathers data to send via a jQuery event, then sends this to the server and waits for a response. On the server, an admin-ajax handler takes the passed data, prepares a response, filters the response, then returns the data in JSON format. The client receives this data and fires a final jQuery event to indicate the data has been received.

The basic process for custom Heartbeat events is:

  1. Add additional fields to the data to be sent (JS heartbeat-send event)
  2. Detect sent fields in PHP, and add additional response fields (heartbeat_received filter)
  3. Process returned data in JS (JS heartbeat-tick)

(You can choose to use only one or two of these events, depending on what functionality you need.)

Using the API

Using the heartbeat API requires two separate pieces of functionality: send and receive callbacks in JavaScript, and a server-side filter to process passed data in PHP.

Sending Data to the Server

When Heartbeat sends data to the server, you can include custom data. This can be any data you want to send to the server, or a simple true value to indicate you are expecting data.

jQuery( document ).on( 'heartbeat-send', function ( event, data ) {
	// Add additional data to Heartbeat data.
	data.myplugin_customfield = 'some_data';
});

Receiving and Responding on the Server

On the server side, you can then detect this data, and add additional data to the response.

/**
 * Receive Heartbeat data and respond.
 *
 * Processes data received via a Heartbeat request, and returns additional data to pass back to the front end.
 *
 * @param array $response Heartbeat response data to pass back to front end.
 * @param array $data     Data received from the front end (unslashed).
 *
 * @return array
 */
function myplugin_receive_heartbeat( array $response, array $data ) {
	// If we didn't receive our data, don't send any back.
	if ( empty( $data['myplugin_customfield'] ) ) {
		return $response;
	}

	// Calculate our data and pass it back. For this example, we'll hash it.
	$received_data = $data['myplugin_customfield'];

	$response['myplugin_customfield_hashed'] = sha1( $received_data );
	return $response;
}
add_filter( 'heartbeat_received', 'myplugin_receive_heartbeat', 10, 2 );

Processing the Response

Back on the frontend, you can then handle receiving this data back.

jQuery( document ).on( 'heartbeat-tick', function ( event, data ) {
	// Check for our data, and use it.
	if ( ! data.myplugin_customfield_hashed ) {
		return;
	}

	alert( 'The hash is ' + data.myplugin_customfield_hashed );
});

Not every feature will need all three of these steps. For example, if you don’t need to send any data to the server, you can use just the latter two steps.