今天遇到一个咨询,客户的woocommerce商城网站中,后台订单显示有个小问题,订单中的姓名之间无空格,woocommerce默认是连在一起的,查看起来可能会点不方便。
处理方法:使用下面的JS代码给姓名之间添加空格:
<script> jQuery(function ($) { // 仅订单后台运行 if (!$('body.post-type-shop_order').length) return; let nameMap = {}; // 1. 抓取、替换 $('input[name$="_first_name"], input[name$="_last_name"]').each(function () { const prefix = $(this).attr('name').replace(/_(first|last)_name/, ''); const $first = $('input[name="' + prefix + '_first_name"]'); const $last = $('input[name="' + prefix + '_last_name"]'); const first = $first.val().trim(); const last = $last.val().trim(); if (first && last) { const noSpace = last + first; const hasSpace = last + ' ' + first; nameMap[noSpace] = hasSpace; } }); // 2. 批量替换 $('.order_data_column .address p:first-child').each(function () { let html = $(this).html(); // 循环匹配 Object.keys(nameMap).forEach(raw => { html = html.replace(raw, nameMap[raw]); }); $(this).html(html); }); }); </script>
代码可以直接复制添加后wp code之类的插件中,Code Type选JavaScript Snippet。
然后在下面的设置中,Location选Admin header,如上图所示,让代码仅在后台执行。最后保存并启用代码就可以了。
最终效果如上图所示。
刚刚把上面的改好,客户那边又又有问题,说是名字和姓氏顺序要调换一下,没办法只能再改一下了,修改后的代码如下所示:
<script> jQuery(function ($) { // 仅订单后台运行 if (!$('body.post-type-shop_order').length) return; let nameMap = {}; // 1. 抓取、替换 $('input[name$="_first_name"], input[name$="_last_name"]').each(function () { const prefix = $(this).attr('name').replace(/_(first|last)_name/, ''); const $first = $('input[name="' + prefix + '_first_name"]'); const $last = $('input[name="' + prefix + '_last_name"]'); const first = $first.val().trim(); // A const last = $last.val().trim(); // B if (first && last) { const noSpace = last + first; // 交换顺序:名 空格 姓 → B A const hasSpace = first + ' ' + last; nameMap[noSpace] = hasSpace; } }); // 2. 批量替换 $('.order_data_column .address p:first-child').each(function () { let html = $(this).html(); Object.keys(nameMap).forEach(raw => { html = html.replace(raw, nameMap[raw]); }); $(this).html(html); }); }); </script>
使用方法和上面一样的,粘贴进入就OK了。
© Copyright 2020~2026. 悦然网络工作室/悦然wordpress建站 专注中小企业wordpress建站 All Rights Reserved.网站地图本站图片来源为Pexels、Pixabay、Freepik、Unsplash等图片库的免费许可,CC0协议;还有部分为自己手绘或AI生成,版权碰瓷请自重!法律服务:law@yueranseo.com蜀ICP备20016391号-1 川公网安备 51011502000367号