WooCommerce感谢页面添加转化跟踪代码完整指南

本文详细介绍了如何在WooCommerce感谢页面添加转化跟踪代码,包含两种实现方法:使用woocommerce_thankyou钩子和wp_head钩子,支持动态插入订单金额、货币和订单ID等关键交易数据。

如何向WooCommerce感谢页面添加转化跟踪代码

作者: Christos Pontikis
发布日期: 2025年5月25日
分类: Woocommerce

要向WooCommerce感谢页面添加转化跟踪代码(以Google Ads为例),并动态插入订单值(如金额、货币、订单ID),请在您的functions.php文件(子主题中)使用以下代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
function custom_conversion_tracking( $order_id ) {
    $order = wc_get_order( $order_id );
?>
    <script>
      gtag("event", "conversion", {
          "send_to": "Tracking-code-here-XXXXXXXXXX",
          "value": <?php echo $order->get_total(); ?>,
          "currency": "<?php echo $order->get_currency(); ?>",
          "transaction_id": <?php echo $order_id; ?>
      });
    </script>
<?php
}
add_action( 'woocommerce_thankyou', 'custom_conversion_tracking' );

如果您希望将代码添加到HEAD中,请使用:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function custom_conversion_tracking(){
    // 在订单接收端点
    if( is_wc_endpoint_url( 'order-received' ) ) :
     // 获取订单ID
    $order_id = absint( get_query_var('order-received') );
    
    if( get_post_type( $order_id ) !== 'shop_order' ) return;
    
    $order = wc_get_order( $order_id );
?>
    <script>
      gtag("event", "conversion", {
          "send_to": "Tracking-code-here-XXXXXXXXXX",
          "value": <?php echo $order->get_total(); ?>,
          "currency": "<?php echo $order->get_currency(); ?>",
          "transaction_id": <?php echo $order_id; ?>
      });
    </script>
<?php
    endif;
}

add_action( 'wp_head', 'custom_conversion_tracking' );

Christos Pontikis
企业家 | 全栈开发工程师 | MediSign Ltd创始人。拥有超过15年设计和开发Web应用程序的专业经验,同时在管理(Web)项目方面也非常有经验。

comments powered by Disqus
使用 Hugo 构建
主题 StackJimmy 设计