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

如何在WordPress Gutenberg主工具栏中添加按钮?

在Gutenberg主工具栏添加自定义按钮的方法

区块工具栏和编辑器顶部的主工具栏是两个独立的挂载节点,前者针对单个区块,后者属于全局编辑器容器,因此需要用不同的API实现。以下是具体实现步骤:

1. 注册并加载自定义脚本

在主题的functions.php或自定义插件中添加代码,注册并加载我们的自定义JS脚本:

function enqueue_custom_gutenberg_main_toolbar() {
    wp_enqueue_script(
        'gutenberg-main-toolbar-btn',
        get_template_directory_uri() . '/js/gutenberg-main-toolbar.js',
        array( 'wp-plugins', 'wp-edit-post', 'wp-element', 'wp-components' ),
        filemtime( get_template_directory() . '/js/gutenberg-main-toolbar.js' ),
        true
    );
}
add_action( 'enqueue_block_editor_assets', 'enqueue_custom_gutenberg_main_toolbar' );

2. 编写JS代码实现按钮

在主题目录下创建js/gutenberg-main-toolbar.js文件,写入以下代码:

const { registerPlugin } = wp.plugins;
const { PluginButton } = wp.editPost;
const { Button } = wp.components;

// 注册全局插件,挂载主工具栏按钮
registerPlugin( 'custom-main-toolbar-button', {
    render() {
        return (
            <PluginButton
                icon="star-filled" // 可替换为WordPress内置图标或自定义SVG代码
                label="我的自定义按钮"
                onClick={() => {
                    // 这里添加按钮点击后的逻辑
                    console.log('主工具栏按钮触发');
                    // 示例:弹出成功提示
                    wp.data.dispatch('core/notices').createNotice(
                        'success',
                        '主工具栏按钮已点击!',
                        { isDismissible: true }
                    );
                }}
            />
        );
    },
} );

补充说明

  • 如果希望把按钮放到主工具栏的「更多选项」下拉菜单中,可以替换PluginButton为PluginMoreMenuItem组件,代码逻辑一致。
  • 自定义图标可以直接传入SVG字符串,比如icon={<svg>...</svg>}。
  • 必须确保依赖的脚本包包含wp-edit-post(主编辑器核心)和wp-plugins(插件注册API),否则代码无法正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 12:45:38