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

本文详细介绍了两种在WooCommerce感谢页面添加Google Ads转化跟踪代码的方法,包括动态插入订单金额、货币和订单ID等关键交易数据的技术实现方案。

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

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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
24
function custom_conversion_tracking(){
    // 在order-received端点
    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' );
comments powered by Disqus
使用 Hugo 构建
主题 StackJimmy 设计