You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在WordPress的functions.php中添加发票信息代码片段时触发致命错误的求助

解决WordPress发票添加自定义字段分行显示的致命错误问题

嘿,我明白你遇到的麻烦了——尝试给发票加自定义字段分行显示却触发了致命错误,大概率是PHP标签嵌套不对,还有过滤器/钩子的使用方式没搞对。我来给你捋清楚解决方案:

问题根源

你之前写的代码里,在已经处于PHP环境的functions.php中又重复写了<?php和?>标签,这会直接导致语法错误;另外,直接echo输出HTML在某些WooCommerce过滤器的上下文里也不合适,因为这类过滤器通常要求你返回修改后的内容,而不是直接输出。

正确的实现方式

根据WooCommerce的最佳实践,我们可以用钩子来安全地添加这些自定义字段,下面给你两种常用的方案:

方案1:将字段插入到订单总计表格中

这个方案会把自定义字段和订单的运费、税费等放在同一个表格里,风格统一:

add_filter('woocommerce_get_order_item_totals', 'add_custom_invoice_fields_to_totals', 10, 3);
function add_custom_invoice_fields_to_totals($total_rows, $order, $tax_display) {
    // 获取自定义字段的值
    $bairro = get_post_meta($order->get_id(), 'bairro', true);
    $complemento = get_post_meta($order->get_id(), 'billing_complemento', true);

    // 只有字段有值的时候才添加行,避免空行
    if (!empty($bairro)) {
        $total_rows['custom_bairro'] = array(
            'label' => __('Bairro:', 'your-text-domain'), // 替换成你的主题文本域
            'value' => esc_html($bairro), // 转义内容防止XSS
        );
    }

    if (!empty($complemento)) {
        $total_rows['custom_complemento'] = array(
            'label' => __('Complemento:', 'your-text-domain'),
            'value' => esc_html($complemento),
        );
    }

    return $total_rows; // 必须返回修改后的数组
}

方案2:在订单表格后添加独立的自定义字段表格

如果你想让这些字段单独显示,可以用这个方案:

add_action('woocommerce_after_order_table', 'add_custom_fields_after_invoice_table');
function add_custom_fields_after_invoice_table($order) {
    $bairro = get_post_meta($order->get_id(), 'bairro', true);
    $complemento = get_post_meta($order->get_id(), 'billing_complemento', true);

    // 至少有一个字段有值才显示表格
    if (!empty($bairro) || !empty($complemento)) {
        echo '<table class="woocommerce-table woocommerce-table--custom-fields shop_table shop_table_responsive">';
        
        if (!empty($bairro)) {
            echo '<tr class="bairro-row">
                    <th>' . __('Bairro:', 'your-text-domain') . '</th>
                    <td>' . esc_html($bairro) . '</td>
                  </tr>';
        }
        
        if (!empty($complemento)) {
            echo '<tr class="complemento-row">
                    <th>' . __('Complemento:', 'your-text-domain') . '</th>
                    <td>' . esc_html($complemento) . '</td>
                  </tr>';
        }
        
        echo '</table>';
    }
}

关键注意事项

  • 替换your-text-domain为你主题的文本域,方便后期翻译。
  • 用esc_html()转义输出内容,这是WordPress的安全规范,防止恶意脚本注入。
  • 确保自定义字段的元键(bairro、billing_complemento)和你实际存储的完全一致,大小写敏感哦。
  • 如果你用的是旧版WooCommerce,可能需要用$order->id代替$order->get_id(),但推荐用后者的最新写法。

内容的提问来源于stack exchange,提问作者trajanoo93

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 03:52:39