函数文档

wp_refresh_post_nonces()

💡 云策文档标注

概述

wp_refresh_post_nonces() 是一个 WordPress 函数,用于在新建/编辑文章屏幕检查 nonce 过期情况并在需要时刷新。它作为 Heartbeat API 的回调函数,处理来自客户端的请求并返回更新后的 nonce 值。

关键要点

  • 函数用途:检查并刷新文章编辑界面的 nonce,确保安全性和会话有效性。
  • 参数:接受三个参数:$response(Heartbeat 响应数组)、$data($_POST 数据数组)、$screen_id(屏幕 ID 字符串)。
  • 返回值:返回更新后的 Heartbeat 响应数组,可能包含新的 nonce 值。
  • 条件检查:仅在接收到特定数据键 'wp-refresh-post-nonces' 时执行,验证 post_id 和用户编辑权限。
  • 生成的 nonce:包括 getpermalinknonce、samplepermalinknonce、closedpostboxesnonce、_ajax_linking_nonce 和 _wpnonce。

代码示例

function wp_refresh_post_nonces( $response, $data, $screen_id ) {
	if ( array_key_exists( 'wp-refresh-post-nonces', $data ) ) {
		$received = $data['wp-refresh-post-nonces'];

		$response['wp-refresh-post-nonces'] = array( 'check' => 1 );

		$post_id = absint( $received['post_id'] );

		if ( ! $post_id ) {
			return $response;
		}

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return $response;
		}

		$response['wp-refresh-post-nonces'] = array(
			'replace' => array(
				'getpermalinknonce'    => wp_create_nonce( 'getpermalink' ),
				'samplepermalinknonce' => wp_create_nonce( 'samplepermalink' ),
				'closedpostboxesnonce' => wp_create_nonce( 'closedpostboxes' ),
				'_ajax_linking_nonce'  => wp_create_nonce( 'internal-linking' ),
				'_wpnonce'             => wp_create_nonce( 'update-post_' . $post_id ),
			),
		);
	}

	return $response;
}

注意事项

  • 此函数与 Heartbeat API 集成,主要用于前端自动刷新 nonce,避免用户因会话过期而丢失数据。
  • 确保在调用前用户具有编辑文章的权限,否则 nonce 不会更新。
  • nonce 刷新依赖于正确的 post_id 和屏幕上下文,错误参数可能导致功能失效。

📄 原文内容

Checks nonce expiration on the New/Edit Post screen and refresh if needed.

Parameters

$responsearrayrequired
The Heartbeat response.
$dataarrayrequired
The $_POST data sent.
$screen_idstringrequired
The screen ID.

Return

array The Heartbeat response.

Source

function wp_refresh_post_nonces( $response, $data, $screen_id ) {
	if ( array_key_exists( 'wp-refresh-post-nonces', $data ) ) {
		$received = $data['wp-refresh-post-nonces'];

		$response['wp-refresh-post-nonces'] = array( 'check' => 1 );

		$post_id = absint( $received['post_id'] );

		if ( ! $post_id ) {
			return $response;
		}

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return $response;
		}

		$response['wp-refresh-post-nonces'] = array(
			'replace' => array(
				'getpermalinknonce'    => wp_create_nonce( 'getpermalink' ),
				'samplepermalinknonce' => wp_create_nonce( 'samplepermalink' ),
				'closedpostboxesnonce' => wp_create_nonce( 'closedpostboxes' ),
				'_ajax_linking_nonce'  => wp_create_nonce( 'internal-linking' ),
				'_wpnonce'             => wp_create_nonce( 'update-post_' . $post_id ),
			),
		);
	}

	return $response;
}

Changelog

Version Description
3.6.0 Introduced.