函数文档

wp_initialize_theme_preview_hooks()

💡 云策文档标注

概述

wp_initialize_theme_preview_hooks() 函数用于在站点编辑器中启用块主题预览功能,通过添加过滤器和动作钩子来实现。该函数应在 pluggable.php 加载后调用,以确保 current_user_can() 等依赖功能可用。

关键要点

  • 函数仅在 URL 参数 wp_theme_preview 非空时执行,添加相关钩子以支持主题预览。
  • 添加的钩子包括:stylesheet 和 template 过滤器(使用 wp_get_theme_preview_path 回调),以及 init 和 admin_head 动作(分别使用 wp_attach_theme_preview_middleware 和 wp_block_theme_activate_nonce 回调)。
  • 调用时机很重要,必须在 pluggable.php 包含之后,以避免 current_user_can() 等函数调用错误。

代码示例

function wp_initialize_theme_preview_hooks() {
    if ( ! empty( $_GET['wp_theme_preview'] ) ) {
        add_filter( 'stylesheet', 'wp_get_theme_preview_path' );
        add_filter( 'template', 'wp_get_theme_preview_path' );
        add_action( 'init', 'wp_attach_theme_preview_middleware' );
        add_action( 'admin_head', 'wp_block_theme_activate_nonce' );
    }
}

注意事项

确保在 pluggable.php 加载后调用此函数,否则可能因 current_user_can() 未定义而导致错误。


📄 原文内容

Add filters and actions to enable Block Theme Previews in the Site Editor.

Description

The filters and actions should be added after pluggable.php is included as they may trigger code that uses current_user_can() which requires functionality from pluggable.php.

Source

function wp_initialize_theme_preview_hooks() {
	if ( ! empty( $_GET['wp_theme_preview'] ) ) {
		add_filter( 'stylesheet', 'wp_get_theme_preview_path' );
		add_filter( 'template', 'wp_get_theme_preview_path' );
		add_action( 'init', 'wp_attach_theme_preview_middleware' );
		add_action( 'admin_head', 'wp_block_theme_activate_nonce' );
	}
}

Changelog

Version Description
6.3.2 Introduced.