回复于:wordpress中为经典编辑器添加 “批量替换”功能
› 社区话题 › wordpress开发 › wordpress中为经典编辑器添加 “批量替换”功能 › 回复于:wordpress中为经典编辑器添加 “批量替换”功能
2025年7月11日 - 上午12:23 #430
NewVFX开发
管理员
对于可视化编辑器下的替换功能,进一步增强功能,添加大小写匹配,替换过程提示,以及未找到匹配选项,将这里的内容替换到话题的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>);
}
});
}
});
});
})();