wordpress中为经典编辑器添加 “批量替换”功能

VFX大学 wordpress开发 wordpress中为经典编辑器添加 “批量替换”功能

正在查看 2 条回复
  • 作者
    帖子
    • #419

      追光
      管理员

      很好,你已经实现了经典编辑器中的 “批量替换”按钮,我们可以对其进行以下增强:


      ✅ 目标优化

      1. 支持文本模式(Text/HTML)

      2. 使用两个输入框(查找 和 替换),而不是两个 prompt()

      3. 更符合用户习惯的界面


      🧩 优化后的代码

      functions.php 中:

      // 添加按钮
      add_filter('mce_buttons', function ($buttons) {
          array_push($buttons, 'batch_replace');
          return $buttons;
      });
      
      // 注册脚本
      add_filter('mce_external_plugins', function ($plugins) {
          $plugins['batch_replace'] = get_stylesheet_directory_uri() . '/js/batch-replace.js';
          return $plugins;
      });

      创建

      /js/batch-replace.js

      (function () {
          tinymce.PluginManager.add('batch_replace', function (editor) {
              editor.addButton('batch_replace', {
                  text: '批量替换',
                  icon: false,
                  onclick: function () {
                      editor.windowManager.open({
                          title: '批量查找与替换',
                          body: [
                              {
                                  type: 'textbox',
                                  name: 'find',
                                  label: '查找内容'
                              },
                              {
                                  type: 'textbox',
                                  name: 'replace',
                                  label: '替换为'
                              }
                          ],
                          onsubmit: function (e) {
                              let content = editor.getContent({ format: 'html' }); // 支持文本/可视化两种模式
                              const find = e.data.find;
                              const replace = e.data.replace;
                              if (!find) return;
      
                              const regex = new RegExp(find, 'g');
                              const updated = content.replace(regex, replace);
                              editor.setContent(updated);
                          }
                      });
                  }
              });
          });
      })();

      📌 注意事项

      1. 支持文本模式

        getContent({ format: ‘html’ }) 会获取完整 HTML,不管是在可视化还是文本视图中都统一处理。

        • TinyMCE 本身是针对“可视化模式”的。

        • 文本模式是 <textarea>,不受 TinyMCE 控制,需要额外处理

    • #423

      追光
      管理员

      ✅ 改进目标:经典编辑器的「文本模式」也添加批量替换按钮

      • 用「两个输入框」替代 prompt,让用户一次性填写“查找”和“替换”;

      • 保持只在 文本模式 下工作;

      • 使用 WordPress 自带的样式,界面美观、符合后台风格;


      🔧 改进后完整代码:

      
      // ###################在文本编辑器 WordPress 编辑器,添加批量替换功能jisongbin########################
      add_action('admin_footer-post.php', 'add_batch_replace_text_mode_only');
      add_action('admin_footer-post-new.php', 'add_batch_replace_text_mode_only');
      
      function add_batch_replace_text_mode_only() {
          ?>
          <style>
              #batch-replace-box {
                  background: #f1f1f1;
                  padding: 10px;
                  margin-top: 10px;
                  border: 1px solid #ccc;
                  display: none;
              }
              #batch-replace-box input {
                  width: 100%;
                  margin-bottom: 6px;
              }
          </style>
          <script>
              jQuery(function ($) {
                  // 创建替换功能的面板
                  const box = $(`
                      <div id="batch-replace-box">
                          <input type="text" id="findText" placeholder="查找..." />
                          <input type="text" id="replaceText" placeholder="替换为..." />
                          <button type="button" class="button button-primary" id="doReplace">执行替换</button>
                      </div>
                  `);
      
                  // 创建触发按钮
                  const btn = $('<button type="button" class="button">批量替换</button>');
                  btn.on('click', function () {
                      box.toggle(); // 显示或隐藏输入面板
                  });
      
                  // 替换逻辑,只针对文本模式
                  box.find('#doReplace').on('click', function () {
                      const find = $('#findText').val();
                      const replace = $('#replaceText').val();
                      if (!find) {
                          alert('请输入查找内容');
                          return;
                      }
      
                      // 正则安全转义
                      const escapedFind = find.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
                      const regex = new RegExp(escapedFind, 'g');
      
                      const editor = $('#content'); // 仅文本编辑器 textarea
                      const val = editor.val();
                      const matchCount = (val.match(regex) || []).length;
                      if (matchCount === 0) return alert('未找到匹配内容');
                      const updated = val.replace(regex, replace);
                      editor.val(updated);
      
                      alert(`替换完成,共替换了 ${matchCount} 处内容`);
                  });
      
                  // 插入面板和按钮,优先插入文本模式工具栏
                  if ($('#ed_toolbar').length) {
                      $('#ed_toolbar').append(btn);
                      btn.after(box);
                  } else {
                      $('#wp-content-wrap').after(btn);
                      btn.after(box);
                  }
              });
          </script>
          <?php
      }
      // #######################批量替换结束#####################
      

      🎯 效果预览:

      • 文本模式下方出现一个「批量替换」按钮;

      • 点击后展开两个输入框:

        • 查找内容

        • 替换为

      • 点击“执行替换”后,立即替换 <textarea> 中的内容(支持多次点击替换);


      📌 限制说明:

      • 仅作用于经典编辑器的「文本模式」;

      • 不影响可视化编辑器(TinyMCE);

      • 不支持正则修饰符(如忽略大小写),如有需要可以扩展;


      如你愿意,也可以进一步封装为可复用插件,或拓展至自定义字段、前端编辑等场景。是否需要我封装成插件版本?

    • #430

      网站开发
      管理员

      对于可视化编辑器下的替换功能,进一步增强功能,添加大小写匹配,替换过程提示,以及未找到匹配选项,将这里的内容替换到话题的js文件中即可。/js/batch-replace.js

      (function () {
      tinymce.PluginManager.add('batch_replace', function (editor) {
      editor.addButton('batch_replace', {
      text: '批量替换',
      icon: false,
      onclick: function () {
      editor.windowManager.open({
      title: '批量查找与替换',
      body: [
      {
      type: 'textbox',
      name: 'find',
      label: '查找内容',
      multiline: false,
      minWidth: 300
      },
      {
      type: 'textbox',
      name: 'replace',
      label: '替换为',
      multiline: false,
      minWidth: 300
      },
      {
      type: 'checkbox',
      name: 'case_sensitive',
      label: '区分大小写'
      }
      ],
      onsubmit: function (e) {
      const find = e.data.find;
      const replace = e.data.replace;
      const caseSensitive = e.data.case_sensitive;
      
      if (!find) {
      editor.windowManager.alert('请输入要查找的内容');
      return;
      }
      
      const content = editor.getContent({ format: 'html' });
      
      // 🔐 安全转义正则中的特殊字符
      const escapedFind = find.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      
      // 🧠 构造正则
      const regex = new RegExp(escapedFind, caseSensitive ? 'g' : 'gi');
      
      // 统计替换次数
      const matchCount = (content.match(regex) || []).length;
      if (matchCount === 0) {
      editor.windowManager.alert('没有找到匹配内容。');
      return;
      }
      
      // 替换内容
      const updated = content.replace(regex, replace);
      editor.setContent(updated);
      
      // ✅ 替换结果提示
      editor.windowManager.alert(<code>替换完成,共替换了 ${matchCount} 处内容。</code>);
      }
      });
      }
      });
      });
      })();
正在查看 2 条回复
  • 在下方一键注册,登录后就可以回复啦。