如何通过theme.json注册core/button自定义区块样式?
目前WordPress核心并不支持直接通过你期望的那种theme.json配置方式来注册core/button的自定义块样式(即直接在styles.blocks.core/button下定义带标签的样式选项)。不过有两种更简洁的替代方案,比你现在用的JS方式更高效:
方案一:用PHP注册块样式(推荐)
这种方式不需要前端加载额外JS,直接在主题的functions.php中添加代码即可,注册后的样式会直接出现在按钮块的「样式」下拉选项里,和默认的fill、outline样式并列:
function register_custom_button_styles() { // 注册蓝色按钮样式 register_block_style( 'core/button', array( 'name' => 'blue-button', 'label' => '蓝色按钮', 'style_handle' => 'your-theme-style', // 替换为你的主题样式表句柄 ) ); // 注册红色按钮样式 register_block_style( 'core/button', array( 'name' => 'red-button', 'label' => '红色按钮', 'style_handle' => 'your-theme-style', ) ); } add_action( 'init', 'register_custom_button_styles' );
接着在你的主题样式表(比如style.css)中添加对应的样式代码:
/* 蓝色按钮样式 */ .wp-block-button.is-style-blue-button .wp-block-button__link { background-color: #3b82f6; color: #ffffff; transition: background-color 0.3s ease; } .wp-block-button.is-style-blue-button .wp-block-button__link:hover { background-color: #2563eb; } /* 红色按钮样式 */ .wp-block-button.is-style-red-button .wp-block-button__link { background-color: #ef4444; color: #ffffff; transition: background-color 0.3s ease; } .wp-block-button.is-style-red-button .wp-block-button__link:hover { background-color: #dc2626; }
方案二:通过theme.json添加自定义类(手动选择)
如果你更倾向于用theme.json配置,可以通过自定义类的方式实现,不过需要用户手动在块的「高级」面板中添加类名:
在你的theme.json中添加以下配置:
{ "settings": { "custom": { "classes": { "core/button": [ { "name": "blue-button", "label": "蓝色按钮" }, { "name": "red-button", "label": "红色按钮" } ] } }, "styles": { "blocks": { "core/button": { ".blue-button": { "backgroundColor": "#3b82f6", "color": "#ffffff", ":hover": { "backgroundColor": "#2563eb" } }, ".red-button": { "backgroundColor": "#ef4444", "color": "#ffffff", ":hover": { "backgroundColor": "#dc2626" } } } } } } }
这种方式的缺点是用户需要手动选择类名,不如方案一的样式下拉选项直观。
总结:目前无法直接通过你期望的theme.json语法注册块样式,推荐用PHP方式实现,更符合WordPress的最佳实践,也更简洁。
内容的提问来源于stack exchange,提问作者Nikolai Lehbrink
相关产品推荐
相关产品推荐

