如何将CMSMasters短代码内容迁移至经典/古腾堡WordPress
解决CMSMasters短代码转WordPress兼容格式的方法
针对你导出的含CMSMasters短代码的内容,有以下几种可行的转换方案:
1. 正则批量提取核心内容
如果只需要保留文本内容,可通过正则表达式批量清理短代码,适用于纯文本为主的文章:
- 用支持正则的文本编辑器(如VS Code)打开导出的XML/CSV文件
- 开启正则查找替换模式:
- 查找:
\[cmsmasters_text.*?\]([\s\S]*?)\[\/cmsmasters_text\] - 替换:
$1 - 该规则会提取
[cmsmasters_text]标签内的所有内容,同时丢弃外层的row、column短代码(若需要保留布局结构,可跳过删除row/column的步骤)
- 查找:
2. 自定义短代码兼容(临时过渡)
若需要保留原有布局样式,可在目标WordPress站点的functions.php中添加自定义短代码解析规则,让WordPress识别CMSMasters短代码:
// 解析CMSMasters文本短代码,直接输出内容 function cmsmasters_text_handler($atts, $content = null) { return !is_null($content) ? do_shortcode($content) : ''; } add_shortcode('cmsmasters_text', 'cmsmasters_text_handler'); // 解析行短代码,转为带样式的div function cmsmasters_row_handler($atts, $content = null) { $atts = shortcode_atts([ 'data_padding_bottom' => '0', 'data_width' => 'boxed' ], $atts); $width_class = $atts['data_width'] === 'boxed' ? 'max-w-screen-md mx-auto' : 'w-full'; return sprintf( '<div class="cmsmasters-row %s" style="padding-bottom: %spx;">%s</div>', esc_attr($width_class), esc_attr($atts['data_padding_bottom']), do_shortcode($content) ); } add_shortcode('cmsmasters_row', 'cmsmasters_row_handler'); // 解析列短代码,转为div容器 function cmsmasters_column_handler($atts, $content = null) { return !is_null($content) ? sprintf('<div class="cmsmasters-column">%s</div>', do_shortcode($content)) : ''; } add_shortcode('cmsmasters_column', 'cmsmasters_column_handler');
添加后导入内容,WordPress会自动渲染这些短代码为标准HTML元素。
3. 转换为古腾堡兼容格式
如果目标是古腾堡编辑器,可按以下步骤操作:
- 先用正则提取纯文本内容(参考方案1)
- 将清理后的内容导入WordPress(用经典编辑器模式)
- 打开文章后,点击编辑器顶部的转换为块按钮,WordPress会自动将纯文本转换为段落块
- 若需要恢复布局,可手动添加古腾堡的“行列”块替代原有的row/column结构
4. Python脚本批量处理XML导出文件
对于大量文章,可编写Python脚本批量清理导出的XML文件:
import re import xml.etree.ElementTree as ET # 加载原始导出文件 tree = ET.parse('original_export.xml') root = tree.getroot() namespaces = {'content': 'http://purl.org/rss/1.0/modules/content/'} # 定义正则规则 text_shortcode = re.compile(r'\[cmsmasters_text.*?\]([\s\S]*?)\[\/cmsmasters_text\]', re.DOTALL) row_shortcode = re.compile(r'\[cmsmasters_row.*?\]([\s\S]*?)\[\/cmsmasters_row\]', re.DOTALL) column_shortcode = re.compile(r'\[cmsmasters_column.*?\]([\s\S]*?)\[\/cmsmasters_column\]', re.DOTALL) # 遍历所有文章内容 for item in root.findall('.//item'): content_elem = item.find('content:encoded', namespaces) if content_elem.text: # 提取文本内容,移除外层短代码 cleaned_content = text_shortcode.sub(r'\1', content_elem.text) cleaned_content = row_shortcode.sub(r'\1', cleaned_content) cleaned_content = column_shortcode.sub(r'\1', cleaned_content) content_elem.text = cleaned_content # 保存处理后的文件 tree.write('cleaned_export.xml', encoding='utf-8', xml_declaration=True)
运行脚本后,用清理后的XML文件导入WordPress即可。
内容的提问来源于stack exchange,提问作者Tahi Reu
相关产品推荐
相关产品推荐

