This is a guide about Google Analytics 4 (GA4), the new version of Google Analytics from Google, which introduces a new way to track user data and adds new features such as cross-device user tracking or AI predictions. Clearly if you are on this page, you already know what it is about, if not, here is a complete blog page.
In this article, I’ll show you how to insert on your WP ecommerce (WooCommerce) site the GA4 Datalayer variable in order to track new orders (on the order-received page) and send all the captured information to Google Tag Manager. If you notice in the code, I’ve used some conditionals to check if the Google Tag Manager Cookies were accepted in the plugin responsible for cookies, in this case Borlabs Cookies.
All you have to do is to insert this code in functions.php:
add_action( 'wp_footer', 'pm_add_gtm_datalayer_code' ); function pm_add_gtm_datalayer_code() { if ( ! is_wc_endpoint_url('order-received') ) return; global $wp; if(function_exists('BorlabsCookieHelper')){ //check if Borlabs cookie plugin is activated if(BorlabsCookieHelper()->gaveConsent('google-tag-manager')) { //load code only when the GTM cookie was accepted in Borlabs // 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 $transaction_id = empty($order->get_transaction_id()) ? $order_id : $order->get_transaction_id(); // The transaction ID ?> <script> dataLayer.push({ ecommerce: null }); // Clear the previous ecommerce object. dataLayer.push({ event: "purchase", ecommerce: { transaction_id: "<?php echo $transaction_id; ?>", value: <?php echo $order->get_total(); ?>, tax: <?php echo $order->get_total_tax(); ?>, shipping: <?php echo $order->get_shipping_total(); ?>, currency: "<?php echo $order->get_currency(); ?>", items: [ <?php // Get and Loop Over Order Items foreach ( $order->get_items() as $item_id => $item ) { $product_id = $item->get_product_id(); $term_names = wp_get_post_terms( $item->get_product_id(), 'product_cat', array('fields' => 'names') ); // Set them as a coma separated string $categories_string = implode(',', $term_names); ?> //items purchased { item_id: "<?php echo $item->get_sku(); ?>", item_name: "<?php echo $item->get_name(); ?>", category: "<?php echo $categories_string; ?>", price: <?php echo $item->get_subtotal(); ?>, quantity: <?php echo $item->get_quantity(); ?> }, <?php } ?> ] } }); </script> <?php endif; } } }