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

如何在WordPress古腾堡编辑器点击区块时打开自定义侧边栏替代区块设置

如何在古腾堡编辑器点击区块时打开自定义侧边栏替代默认设置

你当前的代码会在编辑器加载完成后直接打开自定义侧边栏,但并没有关联到「点击区块」的触发动作,也没有处理默认区块设置侧边栏的显示逻辑。要实现点击区块时自动打开自定义侧边栏并替换默认面板,需要监听区块选中事件并调整侧边栏的切换逻辑。

正确实现代码

import { select, dispatch, subscribe } from '@wordpress/data';
import domReady from '@wordpress/dom-ready';

domReady(() => {
    let previousSelectedBlockId = null;

    // 监听区块选中状态的变化
    const unsubscribe = subscribe(() => {
        const currentSelectedBlock = select('core/block-editor').getSelectedBlock();
        
        // 选中新区块时触发
        if (currentSelectedBlock && currentSelectedBlock.clientId !== previousSelectedBlockId) {
            previousSelectedBlockId = currentSelectedBlock.clientId;
            
            // 关闭默认的区块设置侧边栏(如果已打开)
            if (select('core/edit-post').isEditorSidebarOpened('edit-post/block')) {
                dispatch('core/edit-post').closeGeneralSidebar();
            }
            
            // 打开自定义侧边栏
            dispatch('core/edit-post').openGeneralSidebar('my-plugin/custom-sidebar');
        }
        
        // 取消选中区块时(点击空白处),关闭自定义侧边栏(可选,按需调整)
        if (!currentSelectedBlock && previousSelectedBlockId) {
            previousSelectedBlockId = null;
            dispatch('core/edit-post').closeGeneralSidebar();
        }
    });

    // 若在React组件中使用,记得在组件卸载时取消订阅
    // return () => unsubscribe();
});

前置要求:注册自定义侧边栏

你需要先确保已经通过registerPlugin和PluginSidebar组件注册了my-plugin/custom-sidebar这个自定义侧边栏,示例代码如下:

import { registerPlugin } from '@wordpress/plugins';
import { PluginSidebar } from '@wordpress/edit-post';

registerPlugin('my-plugin-custom-sidebar', {
    render: () => (
        <PluginSidebar
            name="my-plugin/custom-sidebar"
            title="自定义区块设置"
            icon="admin-generic"
        >
            {/* 自定义侧边栏内容区域 */}
            <div className="custom-sidebar-content">
                这里是你的自定义区块设置内容
            </div>
        </PluginSidebar>
    ),
});

代码逻辑说明

  • 通过subscribe监听区块编辑器的状态变化,实时获取当前选中的区块
  • 当检测到新区块被选中时,先关闭默认的区块设置侧边栏,再打开自定义侧边栏
  • 可选逻辑:当用户点击空白处取消区块选中时,自动关闭自定义侧边栏,还原编辑器状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 16:20:16