GA4 Purchase Event for Easy Digital Downloads
Sends a Google Analytics 4 "purchase" event with the order total and downloads when a customer lands on the Easy Digital Downloads purchase confirmation page.
Opens WPIDE on
Code
add_action( 'wp_footer', function () {
if ( ! function_exists( 'edd_is_success_page' ) || ! edd_is_success_page() || ! function_exists( 'edd_get_order_by' ) ) {
return;
}
$session = edd_get_purchase_session();
if ( empty( $session['purchase_key'] ) ) {
return;
}
$order = edd_get_order_by( 'payment_key', $session['purchase_key'] );
if ( ! $order || ! in_array( $order->status, array( 'complete', 'publish' ), true ) || edd_get_order_meta( $order->id, '_wpide_ga4_sent', true ) ) {
return;
}
$items = array();
foreach ( $order->get_items() as $item ) {
$items[] = array(
'item_id' => (string) $item->product_id,
'item_name' => $item->product_name,
'price' => round( (float) $item->total / max( 1, (int) $item->quantity ), 2 ),
'quantity' => (int) $item->quantity,
);
}
$data = array(
'transaction_id' => (string) $order->get_number(),
'value' => round( (float) $order->total, 2 ),
'tax' => round( (float) $order->tax, 2 ),
'currency' => $order->currency,
'items' => $items,
);
echo "<script>window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('event', 'purchase', " . wp_json_encode( $data ) . ");</script>\n";
edd_update_order_meta( $order->id, '_wpide_ga4_sent', time() );
} );
Notes
Needs the GA4 tag (gtag.js) on the page. Uses EDD 3 order functions and sends the event once per order.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.