enqueue_block_assets
云策文档标注
概述
enqueue_block_assets 是一个 WordPress 钩子,在编辑器(Gutenberg)和前端加载块资源后触发。开发者可以利用此钩子添加自定义脚本和样式,以增强块编辑器功能。
关键要点
- 钩子名称:enqueue_block_assets,在 WordPress 5.0.0 版本引入
- 触发时机:在编辑器(Gutenberg)和前端资源加载后执行
- 主要用途:通过 wp_enqueue_script 和 wp_enqueue_style 函数为块编辑器添加自定义功能
- 相关函数:wp_common_block_scripts_and_styles() 用于处理公共块脚本和样式
- 注意事项:从 WordPress 6.3 开始,通过此钩子添加的资源也会加载到编辑器 iframe 中;如需仅限编辑器,可使用 is_admin() 条件判断
代码示例
/**
* Register and enqueue stylesheet for the editor only.
*/
add_action( 'enqueue_block_assets', 'wpdocs_enqueue_editor_styles' );
function wpdocs_enqueue_editor_styles() {
if ( is_admin() ) {
wp_enqueue_style( 'prefix-style', plugins_url( 'style.css', __FILE__ ) );
}
}function wpdocs_mytheme_block_styles() {
wp_enqueue_style( 'testimonial', get_stylesheet_directory_uri() . '/template-parts/blocks/testimonial/testimonial.css' );
wp_enqueue_script( 'testimonial', get_stylesheet_directory_uri() . '/template-parts/blocks/testimonial/testimonial.js' );
}
add_action( 'enqueue_block_assets', 'wpdocs_mytheme_block_styles' );
原文内容
Fires after enqueuing block assets for both editor and front-end.
Description
Call add_action on any hook before ‘wp_enqueue_scripts’.
In the function call you supply, simply use wp_enqueue_script and wp_enqueue_style to add your functionality to the Gutenberg editor.
Source
do_action( 'enqueue_block_assets' );
Changelog
| Version | Description |
|---|---|
| 5.0.0 | Introduced. |
Skip to note 3 content
Marcio Duarte
From version 6.3 onwards, styles and scripts added using
enqueue_block_assets()will be enqueued for the editor iframe. If the intention is to limit styles to the editor only, simply use theis_admin()condition. Example:/** * Register and enqueue stylesheet for the editor only. */ add_action( 'enqueue_block_assets', 'wpdocs_enqueue_editor_styles' ); function wpdocs_enqueue_editor_styles() { if ( is_admin() ) { wp_enqueue_style( 'prefix-style', plugins_url( 'style.css', __FILE__ ) ); } }Skip to note 4 content
Francisco_InstaTienda
function wpdocs_mytheme_block_styles() { wp_enqueue_style( 'testimonial', get_stylesheet_directory_uri() . '/template-parts/blocks/testimonial/testimonial.css' ); wp_enqueue_script( 'testimonial', get_stylesheet_directory_uri() . '/template-parts/blocks/testimonial/testimonial.js' ); } add_action( 'enqueue_block_assets', 'wpdocs_mytheme_block_styles' );