钩子文档

enqueue_block_editor_assets

💡 云策文档标注

概述

enqueue_block_editor_assets 是一个 WordPress 钩子,用于在块编辑器界面加载脚本和样式后触发。开发者应通过 add_action 在 'admin_enqueue_scripts' 之前挂载此钩子,以添加编辑器功能。

关键要点

  • 此钩子在块编辑器资源加载后触发,适用于编辑器界面(如侧边栏或工具栏)的脚本和样式。
  • 使用 wp_enqueue_script 和 wp_enqueue_style 在钩子函数中添加资源。
  • 注意:此钩子仅影响编辑器界面;如需样式化编辑器内容或前端视图,应使用 enqueue_block_assets。
  • 在 Full Site Editor 中,样式文件需包含以 ".wp-block-" 开头的类才能被加载。

代码示例

function wpdocs_enqueue_scripts() {
  $blockPath = '/blocks/index.js';
  wp_enqueue_script(
    'example-block',
    get_template_directory_uri() . $blockPath,
    [ 'wp-blocks', 'wp-element', 'wp-i18n' ],
    filemtime( get_template_directory() . $blockPath )
  );
}
add_action( 'enqueue_block_editor_assets', 'wpdocs_enqueue_scripts' );

注意事项

  • 确保在 'admin_enqueue_scripts' 之前调用 add_action。
  • 避免混淆:enqueue_block_editor_assets 用于编辑器界面,enqueue_block_assets 用于编辑器内容和前端。

📄 原文内容

Fires after block assets have been enqueued for the editing interface.

Description

Call add_action on any hook before ‘admin_enqueue_scripts’.

In the function call you supply, simply use wp_enqueue_script and wp_enqueue_style to add your functionality to the block editor.

Source

do_action( 'enqueue_block_editor_assets' );

Changelog

Version Description
5.0.0 Introduced.

User Contributed Notes

  1. Skip to note 7 content

    Using this method you can enqueue JavaScript file for the editor

    function wpdocs_enqueue_scripts() {
    
      $blockPath = '/blocks/index.js';
      
      // Enqueue the block index.js file
      wp_enqueue_script(
        'example-block', // unique handle
        get_template_directory_uri() . $blockPath,
        [ 'wp-blocks', 'wp-element', 'wp-i18n' ], // required dependencies for blocks
        filemtime( get_template_directory() . $blockPath )
      );
    
    }
    add_action( 'enqueue_block_editor_assets', 'wpdocs_enqueue_scripts' );