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

WordPress编辑器按150词拆分长段落的实现方案求助

在WordPress Gutenberg编辑器中实现文本按150词分段的按钮功能

一、创建自定义插件基础结构

基于你提供的插件框架,先搭建插件核心文件:
创建paragraph-splitter-button文件夹,内部新建paragraph-splitter-button.php作为主插件文件:

<?php
/**
 * Plugin Name:  段落拆分按钮
 * Description:  在Gutenberg编辑器添加按钮,将长文本按约150词拆分
 * Version:      1.0.0
 * Author:       自定义
 * License:      GPL-3.0+
 */

namespace Paragraph_Splitter;

defined( 'ABSPATH' ) or die();

function init_constants() {
    define( 'PARAGRAPH_SPLITTER_URL', untrailingslashit( plugin_dir_url( __FILE__ ) ) );
    define( 'PARAGRAPH_SPLITTER_PATH', untrailingslashit( plugin_dir_path( __FILE__ ) ) );
    define( 'PARAGRAPH_SPLITTER_VERSION', get_file_data( __FILE__, [ 'Version' ], 'plugin' )[0] );
}
add_action( 'plugins_loaded', __NAMESPACE__ . '\init_constants', 1 );

二、注册REST API端点处理文本拆分

Gutenberg是前端环境,需通过REST API调用后端拆分逻辑,在主插件文件中添加以下代码:

// 注册REST路由
function register_rest_routes() {
    register_rest_route(
        'paragraph-splitter/v1',
        '/split-text/',
        [
            'methods' => 'POST',
            'callback' => __NAMESPACE__ . '\split_text_callback',
            'permission_callback' => function() {
                return current_user_can( 'edit_posts' );
            }
        ]
    );
}
add_action( 'rest_api_init', __NAMESPACE__ . '\register_rest_routes' );

// 文本拆分核心逻辑
function split_text_callback( $request ) {
    $text = $request->get_param( 'text' );
    if ( empty( $text ) ) {
        return new WP_Error( 'empty_text', '文本内容不能为空', [ 'status' => 400 ] );
    }

    $sentences = preg_split('/(?<=[.?!;])\s+(?=\p{Lu})/', $text);
    $wordcount = 150;
    $ii = 0;
    $paragraphs = array();
    foreach ( $sentences as $value ) {
        if ( isset($paragraphs[$ii]) ) { 
            $paragraphs[$ii] .= ' ' . $value; // 补充空格避免句子拼接无间隔
        } else { 
            $paragraphs[$ii] = $value; 
        }
        if ( $wordcount < str_word_count($paragraphs[$ii]) ) {
            $ii++;
        }
    }

    $result = implode( "\n\n", $paragraphs );
    return rest_ensure_response( [ 'result' => $result ] );
}

注:若处理中文文本,需替换str_word_count为中文分词函数,并调整正则分割规则适配中文标点。

三、编写Gutenberg编辑器按钮的JS代码

在插件文件夹内新建js/editor-button.js,实现编辑器按钮逻辑:

const { __ } = wp.i18n;
const { PluginDocumentSettingPanel, Button } = wp.components;
const { useDispatch, useSelect } = wp.data;

wp.plugins.registerPlugin( 'paragraph-splitter-button', {
    render() {
        const { editPost } = useDispatch( 'core/editor' );
        const currentContent = useSelect( select => {
            return select( 'core/editor' ).getEditedPostAttribute( 'content' );
        }, [] );

        const handleSplitText = async () => {
            try {
                const response = await fetch( '/wp-json/paragraph-splitter/v1/split-text/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': wpApiSettings.nonce
                    },
                    body: JSON.stringify( { text: currentContent } )
                });

                if ( !response.ok ) throw new Error( '请求失败' );
                const data = await response.json();
                editPost( { content: data.result } );
            } catch ( error ) {
                alert( '文本拆分失败:' + error.message );
            }
        };

        return (
            <PluginDocumentSettingPanel
                name="paragraph-splitter-panel"
                title={ __( '段落拆分工具' ) }
                icon="editor-break"
            >
                <Button variant="primary" onClick={ handleSplitText }>
                    { __( '按150词拆分段落' ) }
                </Button>
            </PluginDocumentSettingPanel>
        );
    }
});

四、加载JS脚本到编辑器

回到主插件文件,添加脚本加载逻辑:

// 加载编辑器脚本
function load_editor_scripts() {
    wp_enqueue_script(
        'paragraph-splitter-editor-script',
        PARAGRAPH_SPLITTER_URL . '/js/editor-button.js',
        [ 'wp-plugins', 'wp-edit-post', 'wp-components', 'wp-data', 'wp-i18n' ],
        PARAGRAPH_SPLITTER_VERSION,
        true
    );

    wp_localize_script(
        'paragraph-splitter-editor-script',
        'wpApiSettings',
        [ 'nonce' => wp_create_nonce( 'wp_rest' ) ]
    );
}
add_action( 'enqueue_block_editor_assets', __NAMESPACE__ . '\load_editor_scripts' );

五、插件使用步骤

  1. 将paragraph-splitter-button文件夹上传至WordPress的wp-content/plugins/目录
  2. 在后台插件管理界面启用「段落拆分按钮」插件
  3. 打开Gutenberg编辑器,右侧设置面板会出现「段落拆分工具」,点击按钮即可完成文本拆分

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 23:20:39