Skip to main content
View Categories

Push Purchase Data to Google Tag Manager DataLayer

2 min read

Related: How to Configure Google Tag Manager to Forward eCommerce Events to GA4

Tracking Custom Purchase Events with Google Tag Manager in WordPress #

When managing conversions in WordPress, especially for booking or eCommerce platforms, it’s crucial to send accurate purchase data to tracking platforms like Google Tag Manager (GTM). The following code snippet is designed to push a custom purchaseCompleted event to the dataLayer, allowing marketers and analysts to capture confirmed purchases reliably.

βœ… Use Case #

This code is part of a custom event system in Homerunner WordPress Plugin. It listens for the homerunner_track_purchase action and pushes purchase details to the dataLayer β€” which Google Tag Manager (GTM) or other tag-based tools can then listen to and forward to platforms like Google Analytics, Meta Pixel, or conversion APIs.

πŸ“¦ What It Tracks #

When a reservation is confirmed, the script pushes the following data:

  • event: 'purchaseCompleted'
  • value: The total value of the transaction
  • transaction_id: Unique order/reservation ID
  • currency: e.g., "USD"
  • user_data.email: Customer’s email address

🧠 Why It Matters #

This makes it easy to:

  • Fire GTM tags when a purchase is confirmed.
  • Sync purchases with Google Analytics, Ads, or CRM systems.
  • Improve tracking accuracy without relying on frontend form submissions.

πŸ›  How It Works #

add_action( 'homerunner_track_purchase', function( $tracking_data, $reservation ) {
    if ( $tracking_data['status'] !== 'confirmed' ) return;

    $value = $tracking_data['ecommerce']['value'];
    $transaction_id = $tracking_data['ecommerce']['transaction_id'];
    $currency = $tracking_data['ecommerce']['currency'];
    $email = $tracking_data['form_values']['email'];

    ?>
    <script type="text/javascript">
        (function() {
            window.dataLayer = window.dataLayer || [];
            dataLayer.push({
                event: 'purchaseCompleted',
                value: <?php echo json_encode( $value ); ?>,
                transaction_id: <?php echo json_encode( $transaction_id ); ?>,
                currency: <?php echo json_encode( $currency ); ?>,
                user_data: {
                    email: <?php echo json_encode( $email ); ?>
                }
            });
        })();
    </script>
    <?php
}, 10, 2 );

πŸ”’ Safe & Reliable #

Using json_encode() ensures that all values (like strings and numbers) are safely embedded in JavaScript without breaking syntax or causing injection vulnerabilities.