函数文档

wp_attach_theme_preview_middleware()

💡 云策文档标注

概述

该函数为 apiFetch 添加一个中间件,用于在预览时设置主题。它通过向 Site Editor 的 API 请求添加 wp_theme_preview URL 参数,使响应模拟指定主题的效果。

关键要点

  • 函数 wp_attach_theme_preview_middleware() 在 WordPress 6.3.0 版本引入。
  • 仅允许具有 switch_themes 权限的用户(如管理员)预览主题,通过 current_user_can() 检查。
  • 使用 wp_add_inline_script() 将中间件代码注入到 wp-api-fetch 脚本中。
  • 中间件通过 wp.apiFetch.createThemePreviewMiddleware() 创建,参数从 $_GET['wp_theme_preview'] 获取并经过安全处理。

代码示例

function wp_attach_theme_preview_middleware() {
	// Don't allow non-admins to preview themes.
	if ( ! current_user_can( 'switch_themes' ) ) {
		return;
	}

	wp_add_inline_script(
		'wp-api-fetch',
		sprintf(
			'wp.apiFetch.use( wp.apiFetch.createThemePreviewMiddleware( %s ) );',
			wp_json_encode( sanitize_text_field( wp_unslash( $_GET['wp_theme_preview'] ) ), JSON_HEX_TAG | JSON_UNESCAPED_SLASHES )
		),
		'after'
	);
}

注意事项

  • 函数依赖于 $_GET['wp_theme_preview'] 参数,需确保在调用前已设置。
  • 使用 sanitize_text_field() 和 wp_unslash() 处理输入,以防止安全漏洞。
  • 相关函数包括 wp_add_inline_script()、wp_json_encode()、current_user_can() 等,用于脚本注入、JSON 编码和权限验证。

📄 原文内容

Adds a middleware to apiFetch to set the theme for the preview.

Description

This adds a wp_theme_preview URL parameter to API requests from the Site Editor, so they also respond as if the theme is set to the value of the parameter.

Source

function wp_attach_theme_preview_middleware() {
	// Don't allow non-admins to preview themes.
	if ( ! current_user_can( 'switch_themes' ) ) {
		return;
	}

	wp_add_inline_script(
		'wp-api-fetch',
		sprintf(
			'wp.apiFetch.use( wp.apiFetch.createThemePreviewMiddleware( %s ) );',
			wp_json_encode( sanitize_text_field( wp_unslash( $_GET['wp_theme_preview'] ) ), JSON_HEX_TAG | JSON_UNESCAPED_SLASHES )
		),
		'after'
	);
}

Changelog

Version Description
6.3.0 Introduced.