title: "Filters and hooks" post_status: publish comment_status: open taxonomy: category: - gutenberg-docs post_tag: - Curating The Editor Experience - How To Guides - Repos


Filters and hooks

The Editor provides numerous filters and hooks that allow you to modify the editing experience. Here are a few.

Editor settings

One of the most common ways to modify the Editor is through the block_editor_settings_all PHP filter, which is applied before settings are sent to the initialized Editor.

The block_editor_settings_all hook passes two parameters to the callback function:

The following example disables the Code Editor for users who cannot activate plugins (Administrators). Add this to a plugin or your theme's functions.php file to test it.

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

For more examples, check out the Editor Hooks documentation that includes the following use cases:

服务端 theme.json 过滤器

theme.json 文件是控制界面选项的强大工具,但它仅支持全局或区块级别的修改,在某些场景下可能显得局限。

例如,在前一节中,我们使用 theme.json 全局禁用了颜色和排版控件。但假设您希望为管理员用户启用颜色设置。

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

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

// 为除管理员外的所有用户禁用颜色控件。
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 类实例。然后,您将符合 theme.json 结构的新数据传递给 update_with( $new_data ) 方法。$new_data 中必须包含 theme.json 版本号。

客户端(编辑器)过滤器

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

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

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

/**
 * 将 Column 区块的间距选项限制为像素单位。
 */
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 过滤器是独特的,因为它允许你根据区块的位置、相邻区块、当前用户的角色等进行设置修改。自定义的可能性非常广泛。

在以下示例中,当 Heading 区块被放置在 Media & Text 区块内时,将禁用其文本颜色控件。

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

/**
 * 当 Heading 区块放置在 Media & Text 区块内时,禁用其文本颜色控件。
 */
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 Filters

Beyond curating the Editor itself, there are many ways that you can modify individual blocks. Perhaps you want to disable particular block supports like background color or define which settings should be displayed by default on specific blocks.

One of the most commonly used filters is block_type_metadata. It allows you to filter the raw metadata loaded from a block's block.json file when a block type is registered on the server with PHP.

The filter takes one parameter:

The $metadata array contains everything you might want to know about a block, from its description and attributes to block supports.

In the following example, background color and gradient support are disabled for Heading blocks.

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' );

You can learn more about the available block filters in the Block Filters documentation.

其他资源