简体   繁体   中英

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

I'm trying to add some google tracking script to my thank you page. I've written this code which successfully injects the tracker into the of the thank you with dynamic values, but I need, instead, to add it within the tags.

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' );

How would I be able to use this code, with the dynamic values in header.php, or is there a hook that targets the tags on the woocommerce thank you page.

You will use the following to inject code on the head tags on "Order received" (thankyou) page:

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;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM