在WP All Import中用通配符实现str_replace批量替换URL
解决WP All Import中替换含动态年月的上传文件URL问题
str_replace仅支持精确字符串匹配,无法处理通配符逻辑,这就是你用uploads/*导致URL混合错误的核心原因。要匹配任意年份(4位数字)和月份(2位数字)的动态路径,必须使用正则表达式替换,WP All Import原生支持preg_replace函数实现该需求。
核心实现代码
假设旧URL格式为http://old-domain.com/wp-content/uploads/2023/05/example.jpg,需替换为http://new-domain.com/wp-content/uploads/2023/05/example.jpg,可使用以下代码:
<?php return preg_replace('/http:\/\/old-domain\.com\/wp-content\/uploads\/\d{4}\/\d{2}\//', 'http://new-domain.com/wp-content/uploads/', $url); ?>
代码细节说明
\d{4}:匹配任意4位数字(对应动态年份)\d{2}:匹配任意2位数字(对应动态月份)- 正则中的
.需转义为\.,避免被当作「匹配任意字符」的特殊符号 - 上述代码仅替换域名部分,保留原有的年月路径;若需连年月段一起替换,直接修改替换后的目标字符串即可
特殊场景适配:移除动态年月路径
如果需要将http://old-domain.com/wp-content/uploads/xxxx/xx/xxx.jpg改为http://new-domain.com/wp-content/uploads/xxx.jpg,代码调整为:
<?php return preg_replace('/\/uploads\/\d{4}\/\d{2}\//', '/uploads/', $url); ?>
使用注意事项
- 在WP All Import中,需在对应字段的编辑框选择「PHP函数」模式,再粘贴代码
- 批量导入前务必先测试少量数据,验证替换结果符合预期
内容的提问来源于stack exchange,提问作者Jonny Quinn
相关产品推荐
相关产品推荐

