将 javascript 代码插入 woocommerce 感谢页面的 head 标签

Insert javascript code into the head tags of the woocommerce thank you page

我正在尝试向我的感谢页面添加一些 google 跟踪脚本。我已经编写了这段代码,它成功地将跟踪器注入到带有动态值的感谢中,但我需要将其添加到标签中。

function mv_google_conversion( $order_id ) {
    $order = new WC_Order( $order_id );
    $currency = $order->get_currency();
    $total = $order->get_total();
    ?>
    <script>
      gtag('event', 'conversion', {
          'send_to': 'AW-746876528/x5W1CLfA8JoBEPDckeQC',
          'value': <?php echo $total; ?>,
          'currency': '<?php echo $currency; ?>',
          'transaction_id': '<?php echo $order_id; ?>'
      });
    </script>
    <?php
  }
  add_action( 'woocommerce_thankyou', 'mv_google_conversion' );

我如何使用此代码以及 header.php 中的动态值,或者是否有针对 woocommerce 感谢页面上的标签的挂钩。

您将使用以下代码在 "Order received" (thankyou) 页面的 head 标签上注入代码:

add_action( 'wp_head', 'my_google_conversion' );
function my_google_conversion(){
    // On Order received endpoint only
    if( is_wc_endpoint_url( 'order-received' ) ) :

    $order_id = absint( get_query_var('order-received') ); // Get order ID

    if( get_post_type( $order_id ) !== 'shop_order' ) return; // Exit

    $order = wc_get_order( $order_id ); // Get the WC_Order Object instance
    ?>
    <script>
      gtag('event', 'conversion', {
          'send_to': 'AW-746876528/x5W1CLfA8JoBEPDckeQC',
          'value': <?php echo $order->get_total(); ?>,
          'currency': '<?php echo $order->get_currency(); ?>',
          'transaction_id': '<?php echo $order_id; ?>'
      });
    </script>
    <?php   
    endif;
}

代码进入您的活动子主题(或活动主题)的 functions.php 文件。已测试并有效。