WooCommerce装箱单自定义字段显示问题:仅当字段有值时显示区块
解决方案
要让delivery-date区块仅在gift_message字段有内容时显示,只需修改最后一段输出装箱单的函数,添加对gift_message内容的判断逻辑:
修改后的代码
add_action( 'wpo_wcpdf_after_customer_notes', 'wpo_wcpdf_delivery_date', 10, 2 ); function wpo_wcpdf_delivery_date ($template_type, $order) { if ($template_type == 'packing-slip') { // 获取并清理备注内容,去除首尾空格 $gift_message = trim( $order->get_meta('gift_message') ); // 仅当备注内容不为空时才输出区块 if ( !empty($gift_message) ) { ?> <div class="delivery-date" style="border: 1px dashed;padding: 8px 10px 10px 10px;margin-top: 5px;min-width: 200px;"> <div><strong>Admin note</strong></div> <div><?php echo wpautop( esc_html($gift_message) ); ?></div> </div> <?php } } }
关键修改点
- 用
trim()去除gift_message首尾空格,避免仅输入空格时误显示空区块 - 添加
!empty($gift_message)判断,只有内容非空时才渲染整个delivery-date容器 - 输出内容时复用
wpautop()和esc_html(),和后台显示逻辑保持一致,保证格式规范与内容安全
可选联动优化
如果希望和后台的is_gift开关绑定(仅当标记为"是"且有备注时显示),可将判断条件调整为:
$is_gift = $order->get_meta('is_gift'); $gift_message = trim( $order->get_meta('gift_message') ); if ( $is_gift == '1' && !empty($gift_message) ) { // 输出区块逻辑 }
内容的提问来源于stack exchange,提问作者adem007
相关产品推荐
相关产品推荐

