Halloween Sale 15% off Ends in See the plans
PHP

GA4 Purchase Event for WooCommerce Orders

Sends a Google Analytics 4 "purchase" event with the order ID, value, tax, shipping and items when a customer reaches the order received page, once per order.

Don’t have WPIDE yet? Install it on your site

Code

add_action( 'woocommerce_thankyou', function ( $order_id ) {
    $order = wc_get_order( $order_id );

    if ( ! $order || $order->get_meta( '_wpide_ga4_purchase_sent' ) ) {
        return;
    }

    $items = array();

    foreach ( $order->get_items() as $item ) {
        $product = $item->get_product();
        $qty     = max( 1, (int) $item->get_quantity() );
        $items[] = array(
            'item_id'   => $product && $product->get_sku() ? $product->get_sku() : (string) $item->get_product_id(),
            'item_name' => $item->get_name(),
            'price'     => round( (float) $order->get_item_total( $item, false ), 2 ),
            'quantity'  => $qty,
        );
    }

    $data = array(
        'transaction_id' => (string) $order->get_order_number(),
        'value'          => round( (float) $order->get_total(), 2 ),
        'tax'            => round( (float) $order->get_total_tax(), 2 ),
        'shipping'       => round( (float) $order->get_shipping_total(), 2 ),
        'currency'       => $order->get_currency(),
        'coupon'         => implode( ',', $order->get_coupon_codes() ),
        'items'          => $items,
    );

    echo "<script>window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('event', 'purchase', " . wp_json_encode( $data ) . ");</script>\n";

    $order->update_meta_data( '_wpide_ga4_purchase_sent', time() );
    $order->save();
}, 20 );

Notes

Needs the GA4 tag (gtag.js) on the page, for example from the Google Analytics 4 snippet. Reloading the thank-you page does not send the event again.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.