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

WordPress+WooCommerce环境Global Site Tag失效functions.php报错求助

代码问题汇总
  • 语法错误1:PHP代码块内直接输出JS/HTML内容,没有正确切换PHP解析模式。PHP代码运行时会将<script>标签当做PHP语法解析,直接触发致命错误。
  • 语法错误2:函数结束后额外多写了一组<?php标签和多余的闭合大括号},不符合PHP语法规范,直接导致站点崩溃。
  • 弃用方法风险:使用new WC_Order()实例化订单、get_product_from_item()获取商品的方法,已经在高版本WooCommerce中被弃用,容易触发兼容报错。
  • 安全缺失:没有对订单ID、订单实例的有效性做判断,当传入的订单ID无效时会直接抛出错误。
修正后的完整代码
<?php

/**
 * Add custom tracking code to the thank-you page
 */
add_action( 'woocommerce_thankyou', 'conversion_tracking' );

function conversion_tracking( $order_id ) {
    // 校验订单ID有效性
    if ( ! $order_id ) {
        return;
    }
    // 安全获取订单实例
    $order = wc_get_order( $order_id );
    if ( ! $order || is_wp_error( $order ) ) {
        return;
    }

    // 关闭PHP模式输出JS代码
    ?>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('event', 'conversion', {
            'send_to': 'AW-954963704/lbfjCPunp_kCEPitrscD',
            'value': '<?php echo $order->get_total(); ?>',
            'currency': '<?php echo $order->get_currency(); ?>',
            'transaction_id': '<?php echo $order_id; ?>'
        });
    </script>
    <?php
    // 重新开启PHP模式执行后续逻辑
    // 订单总额
    $order_total = $order->get_total();

    // 获取订单商品条目
    $line_items = $order->get_items();

    // 循环处理商品条目
    foreach ( $line_items as $item ) {
        // 获取商品实例
        $product = $item->get_product();
        if ( ! $product ) {
            continue;
        }
        // 商品SKU
        $sku = $product->get_sku();
        // 购买数量
        $qty = $item->get_quantity();
        // 商品实付总额(含税、四舍五入)
        $total = $order->get_line_total( $item, true, true );
        // 商品原价总额(折扣前)
        $subtotal = $order->get_line_subtotal( $item, true, true );
    }
}

/*-----------------------------------------------------------------------------------*/
/*  Init theme framework
/*-----------------------------------------------------------------------------------*/
require( 'auxin/auxin-include/auxin.php' );
/*-----------------------------------------------------------------------------------*/

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 00:39:03