钩子文档

allowed_block_types

💡 云策文档标注

概述

allowed_block_types 是一个 WordPress 过滤器,用于控制区块编辑器中允许使用的区块类型。该过滤器已在 WordPress 5.8.0 中弃用,建议改用 allowed_block_types_all 过滤器。

关键要点

  • 过滤器名称:allowed_block_types
  • 参数:$allowed_block_types(布尔值或字符串数组,默认 true 表示支持所有已注册区块类型)和 $post(WP_Post 对象)
  • 弃用状态:自 WordPress 5.8.0 起弃用,推荐使用 allowed_block_types_all 过滤器
  • 用途:根据文章类型或其他条件动态限制可用的区块类型

代码示例

function myplugin_allowed_block_types( $allowed_block_types, $post ) {
    
    switch( $post->post_type ) {
        case 'my_cpt_1':
            return array( 'core/paragraph' );
            break;
        case 'my_cpt_2':
            return array( 'core/paragraph', 'core/heading' );
            break;
        default:
            return true;
    }

    return $allowed_block_types;

}
add_filter( 'allowed_block_types', 'myplugin_allowed_block_types', 10, 2 );

注意事项

  • 在 WordPress 5.6 后,核心嵌入区块(core-embed/*)已被变体(Variations)取代,此过滤器可能不再适用于所有嵌入区块。
  • 过滤时,对于不限制的文章类型应返回布尔值(如 true),否则可能因 $allowed_block_types 期望数组或布尔值而失效。
  • 建议在默认情况下返回 $allowed_block_types 的当前值,以兼容其他钩子的使用。

📄 原文内容

Filters the allowed block types for the editor.

Parameters

$allowed_block_typesbool|string[]
Array of block type slugs, or boolean to enable/disable all.
Default true (all registered block types supported)
$postWP_Post
The post resource data.

Source

$allowed_block_types = apply_filters_deprecated( 'allowed_block_types', array( $allowed_block_types, $post ), '5.8.0', 'allowed_block_types_all' );

Changelog

Version Description
5.8.0 Deprecated. Use the ‘allowed_block_types_all’ filter instead.
5.0.0 Introduced.

User Contributed Notes

  1. Skip to note 5 content

    When filtering for allowed block types, return the boolean for the post types you are not restricting. Otherwise, it won’t work as Nilambar’s example because $allowed_block_types is expecting an array or a boolean.
    This worked for me when filtering allowed blocks for a custom post type. You’ll want to substitute ‘myplugin’ with your namespace and the post types you’re filtering in the switch statement.

    function myplugin_allowed_block_types( $allowed_block_types, $post ) {
    	
    	switch( $post->post_type ) {
            case 'my_cpt_1':
                return array( 'core/paragraph' );
                break;
            case 'my_cpt_2':
                return array( 'core/paragraph', 'core/heading' );
                break;
            default:
                return true;
        }
    
        return $allowed_block_types;
    
    }
    add_filter( 'allowed_block_types', 'myplugin_allowed_block_types', 10, 2 );