Search code examples
javascriptphpwoocommercehook-woocommercegtag.js

Include some javascript code in HEAD on WooCommerce Order received


Goal: I need to include an event snippet for specific tracking on the Woocommerce Order Confirmation page (the page immediately following a purchase). I must pass order_id, currency and total to the tracker. Here is the code I've written:

function wh_CustomReadOrder($order_id)
{
    //getting order object
    $order = wc_get_order($order_id);
    echo  "<script> gtag('event', 'conversion', { 'send_to': 'AW-995109926/CWeECK-epPYBEKbYwNoD', 'value': '".$order->get_total()."', 'currency': '".$order->currency."', 'transaction_id': '".$order_id."' }); </script>";
}
add_action('woocommerce_thankyou', 'wh_CustomReadOrder');

This includes the code correctly on the page and passes the relevant info to the tracker. But this code does not appear in the <head> of the page; it appears in the body. Per instructions this code must be placed in the <head>.

I have not found a snippet plugin that allows for this kind of control. Is there another way I can achieve this?

If I were to include this code on all pages in the <head> but wrap it in an if statement that checks for the url, /checkout/order-received/{order-id}/ and fires if true, is that possible or there another way?


Solution

  • You can use the following to inject your Javascript code in the head on "Order received" page:

    add_action( 'wp_head', 'wc_custom_redirect_after_purchase' );
    function wc_custom_redirect_after_purchase() {
        if ( ! is_wc_endpoint_url('order-received') ) return;
        global $wp;
    
        // If order_id is defined
        if ( isset($wp->query_vars['order-received']) && absint($wp->query_vars['order-received']) > 0 ) :
    
        $order_id       = absint($wp->query_vars['order-received']); // The order ID
        $order          = wc_get_order($order_id ); // The WC_Order object
        
        $send_to        = 'AW-995109926/CWeECK-epPYBEKbYwNoD';
        $transaction_id = empty($order->get_transaction_id()) ? $order_id : $order->get_transaction_id(); // The transaction ID
        
        ?>
        <script type="text/javascript">
        gtag('event', 'conversion', {
            'send_to'       : '<?php echo $send_to; ?>', 
            'value'         : '<?php echo $order->get_total(); ?>', 
            'currency'      : '<?php echo $order->get_currency(); ?>', 
            'transaction_id': '<?php echo $transaction_id; ?>' 
        });
        </script>
        <?php
        endif;
    }
    

    Code goes in functions.php file of the active child theme (or active theme). It should work.