限制可用区块,而不破坏 WordPress 站点编辑器

想限制内容编辑者可以使用的区块时,很容易想到 allowed_block_types_all 过滤器。但如果将它应用于整个站点,就会很快发现站点编辑器无法正常工作:关键布局区块消失,模板也无法加载。

解决办法是根据编辑上下文限定过滤器的作用范围。这样,内容编辑者可以专注于写作,站点设计者也能在站点编辑器中保有完整的灵活性。

函数

add_filter( 'allowed_block_types_all', 'allowed_blocks', 10, 2 );

function allowed_blocks( $allowed, $context ) {
    // Site Editor usually edits these post types.
    if ( isset( $context->post ) && $context->post ) {
        $post_type = $context->post->post_type;

        // Allow all blocks in the Site Editor.
        if ( in_array( $post_type, array( 'wp_template', 'wp_template_part' ), true ) ) {
            return true;
        }

        // Restrict blocks for regular content.
        if ( in_array( $post_type, array( 'post', 'page' ), true ) ) {
            return array(
                'core/paragraph',
                'core/heading',
                'core/image',
            );
        }
    }

    // Fallback: detect the Site Editor screen directly if available.
    if ( function_exists( 'get_current_screen' ) ) {
        $screen = get_current_screen();
        if ( $screen && 'site-editor' === $screen->id ) {
            return true;
        }
    }

    // Another fallback: some contexts expose a name like 'core/edit-site'.
    if ( isset( $context->name ) && 'core/edit-site' === $context->name ) {
        return true;
    }

    return $allowed;
}

为什么这很重要

站点编辑器负责处理 wp_template 和 wp_template_part,必须能够访问全部区块才能正常运行。在全站范围限制区块,会移除布局和设计工具,破坏编辑体验。

这个函数会:

  • 在站点编辑器内开放全部区块。
  • 只对文章和页面的内容限制区块。
  • 提供备用检测方式,以适应不同 WordPress 版本的上下文差异。

结语

根据文章类型和编辑器上下文限定 allowed_block_types_all 过滤器,可以同时获得两方面的好处:作者能够维持内容编辑的一致性,设计者也能完全掌控设计。这是一处小改动,却可能避免日后花上数小时排查令人困惑的问题。

感谢 @bph 和 @psykro 审阅文章并提供反馈。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容