编辑器提供了许多过滤器和钩子,允许你修改编辑体验。以下是一些示例。

编辑器设置

修改编辑器最常见的方法之一是通过 block_editor_settings_all PHP 过滤器,该过滤器在将设置发送到已初始化的编辑器之前应用。

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

以下示例为无法激活插件的用户(管理员)禁用代码编辑器。将此内容添加到插件或主题的 functions.php 文件中以进行测试。

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;
}

查看 编辑器钩子 文档以获取更多示例,其中包括以下用例:

服务器端 theme.json 过滤器

theme.json 文件是控制界面选项的绝佳方式,但它仅允许全局或块级别的修改,在某些场景中这可能是一种限制。

例如,在上一节中,使用 theme.json 全局禁用了颜色和排版控件。但假设你想为管理员用户启用颜色设置。

为了提供更大的灵活性,WordPress 6.1 引入了服务器端过滤器,允许你在四个不同的数据层自定义 theme.json 数据。

在以下示例中,使用 wp_theme_json_data_theme 过滤器更新当前主题的 theme.json 文件中的数据。如果当前用户是管理员,则恢复颜色控件。

// Disable color controls for all users except Administrators.
function example_filter_theme_json_data_theme( $theme_json ){
    $is_administrator = current_user_can( 'edit_theme_options' );

    if ( $is_administrator ) {
        $new_data = array(
            'version'  => 2,
            'settings' => array(
                'color' => array(
                    'background'       => true,
                    'custom'           => true,
                    'customDuotone'    => true,
                    'customGradient'   => true,
                    'defaultGradients' => true,
                    'defaultPalette'   => true,
                    'text'             => true,
                ),
            ),
        );
    }

    return $theme_json->update_with( $new_data );
}
add_filter( 'wp_theme_json_data_theme', 'example_filter_theme_json_data_theme' );

过滤器接收 WP_Theme_JSON_Data class 的一个实例,其中包含相应层的数据。然后,你将新数据以有效的 theme.json 结构传递给 update_with( $new_data ) 方法。$new_data 中需要 theme.json 版本号。

服务器端视图配置过滤器

DataViews 驱动的屏幕(例如页面列表及其快速编辑表单)从服务器获取其配置。动态过滤器 get_entity_view_config_{$kind}_{$name} 允许你为特定实体自定义该配置,其中动态部分是实体类型(例如 postType)和名称(例如 page),小写——因此 postType/page 实体映射到 get_entity_view_config_posttype_page 过滤器。

目前,该过滤器由以下站点编辑器屏幕使用:

页面过滤器名称
页面get_entity_view_config_posttype_page
模板get_entity_view_config_posttype_wp_template
部分get_entity_view_config_posttype_wp_template_part
模式get_entity_view_config_posttype_wp_block

每个实体(和屏幕)有四个方面可配置:

  • default_view:默认的 DataViews 配置(例如,哪些字段可见,默认排序顺序等)。
  • default_layouts:默认的 DataViews 布局(例如,用户可以选择的可用布局)。
  • view_list:侧边栏中显示的预配置视图(例如,“全部”、“已发布”、“草稿”等)。
  • form:用于快速编辑表单的 DataForm 配置(例如,表单中显示的字段及其顺序)。

查看 视图配置参考 以了解每个属性的描述。

每个过滤器回调接收一个 Gutenberg_View_Config_Data 对象,其中包含给定实体的配置,它可以通过调用其方法(见下文)并返回该对象来更改。

例如,通过钩入此过滤器更新页面的视图配置:

function example_filter_page_view_config( $data ) {
    // Modify the configuration...

    return $data;
}
add_filter( 'get_entity_view_config_posttype_page', 'example_filter_page_view_config' );

过滤器优先级

在默认优先级(10)或更高优先级钩入回调。低于 10 的优先级保留给 WordPress 核心,它使用它们来构建屏幕启动时使用的配置。在此之前注册的回调会在核心完成配置组装之前运行,因此其更改会被覆盖。

使用合并更新条目

过滤器回调接收一个 Gutenberg_View_Config_Data 对象,其中编码了实体的当前视图配置。要更新给定配置,调用其 merge( $patch, $version ) 方法,其中:

  • $patch,包含要合并到现有配置中的新数据的数组。
  • $version,整数,是正在合并的数据的版本。目前应为 1。

例如,以下过滤器回调应用于页面屏幕。它将默认视图类型设置为网格,按升序标题对网格进行排序,并使 date 字段可见(除了现有字段)。它还将 my_custom_field 附加到快速编辑 form,保留表单的现有字段(请注意,目前无法从服务器注册字段)。

合并到列表中的条目始终追加到其末尾;选择新条目落地的位置目前尚不支持。

function example_filter_page_view_config( $data ) {
    $patch = array(
        'default_view' => array(
            'type'   => 'grid',
            'sort'   => array(
                'field'     => 'title',
                'direction' => 'asc',
            ),
            'fields' => array( 'date' ),
        ),
        'form'         => array(
            'fields' => array( 'my_custom_field' ),
        ),
    );
    $data->merge( $patch, 1 );

    return $data;
}
add_filter( 'get_entity_view_config_posttype_page', 'example_filter_page_view_config' );

使用 remove 移除条目

Gutenberg_View_Config_Data 对象有一个 remove( $spec, $version ) 方法,允许您从配置中移除条目。

  • $spec,一个数组,指定要移除的条目。
  • $version,整数,正在修改的数据的版本。目前应为 1。

以下过滤器回调适用于 页面 屏幕。它从 DataViews 中可见字段列表中移除 status 字段,并从快速编辑表单中移除 format 字段:

function example_page_view_config_remove( $data ) {
    $spec = array(
        'default_view' => array(
            'fields' => array( 'status' ),
        ),
        'form'         => array(
            'fields' => array( 'format' ),
        ),
    );
    $data->remove( $spec, 1 );

    return $data;
}
add_filter( 'get_entity_view_config_posttype_page', 'example_page_view_config_remove' );

使用 replace 更新条目

还有一个 replace( $patch, $version ) 方法。它的工作方式与 merge 类似,但有一个区别:它们如何处理数字索引数组(例如 fields => array( 'date', 'author' ))。在 merge 会将新项添加到索引数组中时,replace 将替换整个列表。

例如,此代码使用 merge 将 date 添加到可见字段列表中,并将 my_custom_field 附加到快速编辑表单,同时保留当前条目:

function example_filter_page_view_config( $data ) {
    $patch = array(
        'default_view' => array(
            'fields' => array( 'date' ),
        ),
        'form'         => array(
            'fields' => array( 'my_custom_field' ),
        ),
    );
    $data->merge( $patch, 1 );

    return $data;
}
add_filter( 'get_entity_view_config_posttype_page', 'example_filter_page_view_config' );

然而,此代码使用 replace 将可见字段列表替换为仅包含 date,并将快速编辑表单的整个字段列表替换为 date 和 my_custom_field:

function example_filter_page_view_config( $data ) {
    $patch = array(
        'default_view' => array(
            'fields' => array( 'date' ),
        ),
        'form'         => array(
            'fields' => array( 'date', 'my_custom_field' ),
        ),
    );
    $data->replace( $patch, 1 );

    return $data;
}
add_filter( 'get_entity_view_config_posttype_page', 'example_filter_page_view_config' );

使用 set 设置条目

还有一个 set( $patch, $version ) 方法:

  • $patch,一个包含其命名的顶级键的新值的数组。
  • $version,整数,正在修改的数据的版本。目前应为 1。

与 merge 和 replace 一样,set 仅处理补丁命名的顶级键。区别在于深度。在 merge 和 replace 将命名键的值逐个合并到当前键时,set 会整体替换整个值,丢弃该键之前持有的任何内容。

当回调拥有某个键并希望将其固定为确切形状,而不让继承的默认值通过逐键合并泄露时,请使用它。

例如,此代码应用于 页面 屏幕,使 default_view 和 form 完全成为给定的配置,丢弃它们拥有的任何其他属性(default_view 的页面大小、过滤器等,以及表单的默认字段和布局):

function example_filter_page_view_config( $data ) {
    $patch = array(
        'default_view' => array(
            'type'   => 'grid',
            'fields' => array( 'date' ),
        ),
        'form'         => array(
            'layout' => array( 'type' => 'panel' ),
            'fields' => array( 'excerpt', 'date', 'my_custom_field' ),
        ),
    );
    $data->set( $patch, 1 );

    return $data;
}
add_filter( 'get_entity_view_config_posttype_page', 'example_filter_page_view_config' );

客户端(编辑器)过滤器

WordPress 6.2 引入了一个新的客户端过滤器,允许您在编辑器渲染之前修改块级别的 theme.json 设置。

该过滤器称为 blockEditor.useSetting.before,可以在 JavaScript 代码中如下使用:

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

/**
 * Limit the Column block's spacing options to pixels.
 */
addFilter(
    'blockEditor.useSetting.before',
    'example/useSetting.before',
    ( settingValue, settingName, clientId, blockName ) => {
        if ( blockName === 'core/column' && settingName === 'spacing.units' ) {
            return [ 'px' ];
        }
        return settingValue;
    }
);

此示例将限制 Column 块可用的间距单位仅为像素。如上所述,可以使用 theme.json 过滤器或在主题的 theme.json 文件中直接使用块级设置应用类似的限制。

然而,blockEditor.useSetting.before 过滤器是独特的,因为它允许您根据块的位置、相邻块、当前用户的角色等修改设置。定制的可能性非常广泛。

在以下示例中,每当块放置在媒体和文本块内时,标题块中的文本颜色控件将被禁用。

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

/**
 * Disable text color controls on Heading blocks when placed inside of Media & Text blocks.
 */
addFilter(
    'blockEditor.useSetting.before',
    'example/useSetting.before',
    ( settingValue, settingName, clientId, blockName ) => {
        if ( blockName === 'core/heading' ) {
            const { getBlockParents, getBlockName } =
                select( 'core/block-editor' );
            const blockParents = getBlockParents( clientId, true );
            const inMediaText = blockParents.some(
                ( ancestorId ) =>
                    getBlockName( ancestorId ) === 'core/media-text'
            );

            if ( inMediaText && settingName === 'color.text' ) {
                return false;
            }
        }

        return settingValue;
    }
);

块过滤器

除了定制编辑器本身外,还有许多方法可以修改单个块。也许您想禁用特定的块支持(如背景颜色)或定义哪些设置应在特定块上默认显示。

最常用的过滤器之一是 block_type_metadata。它允许您在服务器端使用 PHP 注册块类型时过滤从块的 block.json 文件加载的原始元数据。

该过滤器接受一个参数:

  • $metadata (array) – 用于注册块类型的从 block.json 加载的元数据。

$metadata 数组包含您可能想了解有关块的所有内容,从其描述和 属性 到块 支持。

在以下示例中,禁用了标题块的背景颜色和渐变支持。

function example_disable_heading_background_color_and_gradients( $metadata ) {

    // Only apply the filter to Heading blocks.
    if ( ! isset( $metadata['name'] ) || 'core/heading' !== $metadata['name'] ) {
        return $metadata;
    }

    // Check if 'supports' key exists.
    if ( isset( $metadata['supports'] ) && isset( $metadata['supports']['color'] ) ) {

        // Remove Background color and Gradients support.
        $metadata['supports']['color']['background'] = false;
        $metadata['supports']['color']['gradients']  = false;
    }

    return $metadata;
}
add_filter( 'block_type_metadata', 'example_disable_heading_background_color_and_gradients' );

您可以在 块过滤器 文档中了解有关可用块过滤器的更多信息。

其他资源