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

如何在自定义WordPress插件中添加Gutenberg富文本工具栏编辑功能

实现方案:在自定义WP插件后台字段中复用Gutenberg文本格式化工具栏

1. 注册后台页面并加载Gutenberg依赖

先在插件里注册专属后台页面,只在这个页面加载Gutenberg的必要资源,避免拖慢其他后台页面:

add_action('admin_menu', 'my_custom_plugin_add_admin_page');
function my_custom_plugin_add_admin_page() {
    add_menu_page(
        '自定义文本编辑器',
        '文本编辑器',
        'manage_options',
        'my-custom-text-editor',
        'my_custom_plugin_render_admin_page',
        'dashicons-editor-textcolor',
        6
    );
}

add_action('admin_enqueue_scripts', 'my_custom_plugin_enqueue_assets');
function my_custom_plugin_enqueue_assets($hook) {
    // 仅在目标页面加载资源
    if ($hook !== 'toplevel_page_my-custom-text-editor') {
        return;
    }

    // 加载Gutenberg核心组件的脚本和样式
    wp_enqueue_script('wp-blocks');
    wp_enqueue_script('wp-element');
    wp_enqueue_script('wp-rich-text');
    wp_enqueue_script('wp-components');
    
    wp_enqueue_style('wp-components');
    wp_enqueue_style('wp-edit-post');
    
    // 加载自定义React脚本
    wp_enqueue_script(
        'my-custom-rich-text',
        plugin_dir_url(__FILE__) . 'js/custom-rich-text.js',
        array('wp-element', 'wp-rich-text', 'wp-components'),
        time(),
        true
    );

    // 把已保存的文本内容传递给前端
    $saved_content = get_option('my_custom_text_content', '');
    wp_localize_script('my-custom-rich-text', 'MyCustomTextEditor', array(
        'initialContent' => $saved_content
    ));
}

// 渲染后台页面容器
function my_custom_plugin_render_admin_page() {
    echo '<div class="wrap"><h1>自定义文本编辑器</h1><div id="my-custom-rich-text-container"></div></div>';
}

2. 编写前端React脚本(custom-rich-text.js)

直接用Gutenberg的RichText组件,它自带格式化工具栏,完全不用套完整的Block框架:

const { useState } = wp.element;
const { RichText } = wp.blockEditor;
const { Button } = wp.components;

function CustomRichTextEditor() {
    const [content, setContent] = useState(MyCustomTextEditor.initialContent);

    const handleSave = () => {
        // 用AJAX保存内容
        fetch(ajaxurl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-WP-Nonce': wpApiSettings.nonce
            },
            body: new URLSearchParams({
                action: 'save_my_custom_text',
                content: content
            })
        })
        .then(response => response.json())
        .then(data => {
            alert(data.success ? '内容已保存' : '保存失败');
        });
    };

    return (
        <div className="custom-rich-text-editor">
            <RichText
                tagName="div"
                value={content}
                onChange={setContent}
                allowedFormats={[
                    'core/bold',
                    'core/italic',
                    'core/link',
                    'core/strikethrough',
                    'core/underline'
                ]} // 按需保留格式化选项
                placeholder="输入并格式化你的文本..."
            />
            <Button variant="primary" onClick={handleSave} style={{ marginTop: '10px' }}>
                保存内容
            </Button>
        </div>
    );
}

// 把组件挂载到后台容器里
wp.element.render(
    <CustomRichTextEditor />,
    document.getElementById('my-custom-rich-text-container')
);

3. 处理AJAX保存请求

在插件PHP文件里添加保存逻辑:

add_action('wp_ajax_save_my_custom_text', 'my_custom_plugin_save_text');
function my_custom_plugin_save_text() {
    check_ajax_referer('wp_rest'); // 验证权限

    if (!current_user_can('manage_options')) {
        wp_send_json_error('无操作权限');
    }

    $content = isset($_POST['content']) ? wp_kses_post($_POST['content']) : '';
    update_option('my_custom_text_content', $content);

    wp_send_json_success('内容已保存');
}

关键细节

  • 不用整Block:RichText是Gutenberg原生的富文本组件,自带格式化工具栏,完全满足你的需求,没必要接入完整的Block体系。
  • 自定义工具栏:通过allowedFormats可以精准控制显示哪些格式化按钮,不需要的直接去掉就行。
  • 性能优化:只在目标页面加载Gutenberg资源,不会影响其他后台页面的运行速度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 03:05:33