You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅在使用指定Block Pattern时为WordPress入队样式表

WordPress 6.3区块模式(Block Pattern)的使用与检测痛点

在WordPress 6.3的块编辑器(Gutenberg)中,可注册由预先配置好的块集合组成的区块模式,注册代码示例如下:

add_action('init', function () {

    register_block_pattern(
        'my_test_pattern',
        array(
            'title' => 'My Test Pattern',
            "categories" => ['text'],
            'description' => 'Test',
            'content' => "<!-- wp:paragraph -->
            <p>Something</p>
            <!-- /wp:paragraph -->",
        )
    );

});

我们可以通过以下代码检测指定区块模式是否已在全站完成注册:

WP_Block_Patterns_Registry::get_instance()->is_registered("my_test_pattern")

但目前WordPress没有提供类似检测区块的has_block("block-name")函数的has_pattern函数,无法判断某个区块模式是否被实际使用,这就导致我们无法仅在使用了该模式的页面中入队对应的样式表。

问题根源与补充思路

问题核心在于:区块的名称会被保存到文章的post_content中,但区块模式不会——文章内容里只会存储模式包含的具体区块。

一种可行但较为繁琐的解决方案是:创建自定义区块,通过InspectorControl添加自定义的模式名字段,在渲染时根据该字段的值来入队对应的CSS文件。

内容的提问来源于stack exchange,提问作者Walrus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 11:52:05