title: "编辑器钩子" post_status: publish comment_status: open taxonomy: category: - gutenberg-docs post_tag: - Filters - Reference Guides - Repos


编辑器钩子

WordPress 提供了多个 API,允许您修改编辑器体验。

编辑器设置

修改编辑器最常见的方式之一是通过 block_editor_settings_all PHP 过滤器,该过滤器在设置发送到初始化的编辑器之前应用。此过滤器允许插件和主题作者对编辑器的行为进行广泛控制。

在 WordPress 5.8 之前,此钩子称为 block_editor_settings,现已弃用。如果您需要支持旧版本的 WordPress,可能需要一种方法来检测应使用哪个过滤器。您可以通过检查 WP_Block_Editor_Context 类是否存在来判断 block_editor_settings 是否安全使用,该类在 5.8 版本中引入。

block_editor_settings_all 钩子向回调函数传递两个参数:

以下示例修改了最大上传文件大小。将此代码添加到插件或主题的 functions.php 文件中进行测试。

add_filter( 'block_editor_settings_all', 'example_filter_block_editor_settings_when_post_provided', 10, 2 );

function example_filter_block_editor_settings_when_post_provided( $editor_settings, $editor_context ) {
    if ( ! empty( $editor_context->post ) ) {
        $editor_settings['maxUploadFileSize'] = 12345;
    }
    return $editor_settings;
}

编辑器设置有数十个,无法在此文档文章中一一列出,但以下是使用 block_editor_settings_all 过滤器可以实现的一些示例。

要查看所有可用设置,请打开编辑器,然后在浏览器的 开发者工具 中打开控制台。输入命令 wp.data.select( 'core/block-editor' ).getSettings() 以显示所有编辑器设置的当前值。

Restrict code editor access

The codeEditingEnabled, which defaults to true, controls whether the user can access the code editor in addition to the visual editor. There may be instances where you don't want certain users to be able to access this view.

If this setting is set to false, the user will not be able to switch between visual and code editor. The option in the settings menu will not be available, and the keyboard shortcut for switching editor types will not fire. Here's an example:

add_filter( 'block_editor_settings_all', 'example_restrict_code_editor' );

function example_restrict_code_editor( $settings ) {
    $can_active_plugins = current_user_can( 'activate_plugins' );

    // Disable the Code Editor for users that cannot activate plugins (Administrators).
    if ( ! $can_active_plugins ) {
        $settings[ 'codeEditingEnabled' ] = false;
    }

    return $settings;
}

限制可视化编辑器访问权限

codeEditingEnabled 设置类似,richEditingEnabled 允许您控制谁可以访问可视化编辑器。若设为 true,用户即可使用可视化编辑器编辑内容。

该设置默认返回 user_can_richedit 函数的值。该函数会检查用户是否能够访问可视化编辑器,以及用户的浏览器是否支持此功能。

设置默认图片尺寸

在编辑器中,图片默认设置为 large 尺寸。你可以使用 imageDefaultSize 设置来修改此默认值,这在配置了自定义图片尺寸时尤其有用。以下示例将默认图片尺寸更改为 medium

add_filter( 'block_editor_settings_all', 'example_set_default_image_size' );

function example_set_default_image_size( $settings ) {
    $settings['imageDefaultSize'] = 'medium';
    return $settings;
}

禁用 Openverse

默认情况下,所有 WordPress 站点都启用了 Openverse 集成,该功能由 enableOpenverseMediaCategory 设置控制。如需禁用 Openverse,请应用以下过滤器:

add_filter( 'block_editor_settings_all', 'example_disable_openverse' );

function example_disable_openverse( $settings ) {
    $settings['enableOpenverseMediaCategory'] = false;
    return $settings;
}

禁用字体库

字体库允许用户在网站上安装新字体,该功能默认启用,由 fontLibraryEnabled 设置控制。如需禁用字体库,请应用以下过滤器:

add_filter( 'block_editor_settings_all', 'example_disable_font_library' );

function example_disable_font_library( $settings ) {
    $settings['fontLibraryEnabled'] = false;
    return $settings;
}

禁用区块检查器选项卡

大多数区块在检查器中会显示两个选项卡,一个用于设置,另一个用于样式。你可以使用 blockInspectorTabs 设置来禁用这些选项卡。

add_filter( 'block_editor_settings_all', 'example_disable_inspector_tabs_by_default' );

function example_disable_inspector_tabs_by_default( $settings ) {
    $settings['blockInspectorTabs'] = array( 'default' => false );
    return $settings;
}

你也可以修改哪些区块拥有检查器选项卡。以下是一个为特定区块禁用选项卡的示例。

add_filter( 'block_editor_settings_all', 'example_disable_tabs_for_my_custom_block' );

function example_disable_tabs_for_my_custom_block( $settings ) {
    $current_tab_settings = _wp_array_get( $settings, array( 'blockInspectorTabs' ), array() );
    $settings['blockInspectorTabs'] = array_merge(
        $current_tab_settings,
        array( 'my-plugin/my-custom-block' => false )
    );

    return $settings;
}

区块目录

区块目录允许用户直接从 WordPress.org 的插件目录在编辑器中安装新的区块插件。您可以通过移除加载该功能的操作来禁用它,该操作是 wp_enqueue_editor_block_directory_assets。为此,请使用 remove_action,如下所示:

remove_action( 'enqueue_block_editor_assets', 'wp_enqueue_editor_block_directory_assets' );

区块模式

默认情况下,远程模式(例如来自 WordPress.org 模式目录 的模式)在编辑器中可供用户使用。此功能由 should_load_remote_block_patterns 控制,其默认值为 true。您可以通过将过滤器设置为 false (__return_false) 来禁用远程模式。

add_filter( 'should_load_remote_block_patterns', '__return_false' );

编辑器功能

以下过滤器可用于扩展编辑器中的功能。

editor.PostFeaturedImage.imageSize

您可以使用此过滤器来修改文章特色图片组件中显示的图片尺寸。默认值为 'post-thumbnail',当媒体对象中不存在指定的图片尺寸时,将回退到 full 尺寸。此过滤器仿照了经典编辑器中的 admin_post_thumbnail_size 过滤器。

import { addFilter } from '@wordpress/hooks';

const withImageSize = function ( size, mediaId, postId ) {
    return 'large';
};

addFilter(
    'editor.PostFeaturedImage.imageSize',
    'my-plugin/with-image-size',
    withImageSize
);

editor.PostPreview.interstitialMarkup

You can also filter the interstitial message shown when generating previews. Here's an example:

import { addFilter } from '@wordpress/hooks';

const customPreviewMessage = function () {
    return '<b>Post preview is being generated!</b>';
};

addFilter(
    'editor.PostPreview.interstitialMarkup',
    'my-plugin/custom-preview-message',
    customPreviewMessage
);

media.crossOrigin

此过滤器用于为跨域媒体元素(即 <audio><img><link><script><video>)设置或修改 crossOrigin 属性。有关 crossOrigin 属性、其取值以及如何应用于各元素的更多信息,请参阅此文章

一个实际应用示例是在图片块的转换功能中,允许跨域图片在 <canvas> 中使用。示例如下:

import { addFilter } from '@wordpress/hooks';

addFilter(
    'media.crossOrigin',
    'my-plugin/with-cors-media',
    // 回调函数接受第二个参数 `mediaSrc`,它引用
    // 实际跨域媒体的 URL,如果您希望基于此 URL
    // 决定 crossOrigin 的值,这将非常有用。
    ( crossOrigin, mediaSrc ) => {
        if ( mediaSrc.startsWith( 'https://example.com' ) ) {
            return 'use-credentials';
        }
        return crossOrigin;
    }
);

编辑器 REST API 预加载路径

您可以使用 block_editor_rest_api_preload_paths 过滤器来修改用于为区块编辑器预加载常用数据的 REST API 路径数组。以下是一个示例:

add_filter( 'block_editor_rest_api_preload_paths', 'example_filter_block_editor_rest_api_preload_paths_when_post_provided', 10, 2 );

function example_filter_block_editor_rest_api_preload_paths_when_post_provided( $preload_paths, $editor_context ) {
    if ( ! empty( $editor_context->post ) ) {
        array_push( $preload_paths, array( '/wp/v2/blocks', 'OPTIONS' ) );
    }
    return $preload_paths;
}

Logging errors

A JavaScript error in a part of the UI shouldn't break the whole app. To solve this problem for users, React library uses the concept of an "error boundary". Error boundaries are React components that catch JavaScript errors anywhere in their child component tree and display a fallback UI instead of the component tree that crashed.

The editor.ErrorBoundary.errorLogged action allows you to hook into the Error Boundaries and gives you access to the error object.

You can use this action to get hold of the error object handled by the boundaries. For example, you may want to send them to an external error-tracking tool. Here's an example:

import { addAction } from '@wordpress/hooks';

addAction(
    'editor.ErrorBoundary.errorLogged',
    'mu-plugin/error-capture-setup',
    ( error ) => {
        // Error is the exception's error object. 
        // You can console.log it or send it to an external error-tracking tool.
        console.log ( error );
    }
);