如何在特定页面模板/文章类型中移除核心古腾堡区块
在特定文章类型/页面模板中移除古腾堡区块(替代已弃用钩子)
WordPress官方已弃用allowed_block_types钩子,要求改用allowed_block_types_all过滤器来控制古腾堡编辑器的可用区块。以下是适配后的实现方案,支持针对特定文章类型、页面模板移除指定区块。
官方弃用提示
apply_filters_deprecated( 'allowed_block_types', bool|string[] $allowed_block_types, WP_Post $post )警告:此钩子已被弃用,请改用
allowed_block_types_all过滤器。
失效代码适配方案
原基于allowed_block_types的代码无法运行,以下是改用allowed_block_types_all后的完整代码:
针对特定文章类型的处理
add_filter('allowed_block_types_all', function($allowed_block_types, $block_editor_context) { // 确保当前处于文章编辑上下文 if (!isset($block_editor_context->post)) { return $allowed_block_types; } $post = $block_editor_context->post; // 定义基础允许的区块列表 $allowed_blocks = [ 'core/shortcode', 'core/image', 'core/gallery', 'core/heading', 'core/quote', ]; // 页面类型保留所有默认区块 if ($post->post_type === 'page') { return $allowed_block_types; } // 其他文章类型移除指定ACF区块 else { $blocks_to_remove = [ 'acf/editor-intro', ]; return array_diff($allowed_blocks, $blocks_to_remove); } }, 10, 2);
针对特定页面模板的处理
如果需要针对某个自定义页面模板(比如template-custom.php)移除区块,可以在代码中加入模板判断:
add_filter('allowed_block_types_all', function($allowed_block_types, $block_editor_context) { if (!isset($block_editor_context->post)) { return $allowed_block_types; } $post = $block_editor_context->post; $allowed_blocks = [ 'core/shortcode', 'core/image', 'core/gallery', 'core/heading', 'core/quote', ]; // 获取当前页面使用的模板 $current_template = get_page_template_slug($post->ID); // 针对指定模板移除特定区块 if ($post->post_type === 'page' && $current_template === 'template-custom.php') { $blocks_to_remove = [ 'core/gallery', 'core/quote', ]; return array_diff($allowed_blocks, $blocks_to_remove); } // 普通页面保留所有区块 elseif ($post->post_type === 'page') { return $allowed_block_types; } // 非页面类型移除指定ACF区块 else { $blocks_to_remove = [ 'acf/editor-intro', ]; return array_diff($allowed_blocks, $blocks_to_remove); } }, 10, 2);
关键说明
allowed_block_types_all钩子的第二个参数是$block_editor_context,需从中获取当前编辑的文章对象$block_editor_context->post- 必须先判断文章对象是否存在,避免在站点设置等非文章编辑场景触发错误
- 使用
array_diff()可以快速从允许的区块列表中剔除不需要的区块 - 若要允许所有区块,直接返回
true即可;若要完全自定义允许列表,直接返回指定数组即可
内容的提问来源于stack exchange,提问作者Mahesh Thorat
相关产品推荐
相关产品推荐

