GA4 begin_checkout Event for WooCommerce
Sends a GA4 "begin_checkout" event with the cart value and items when the customer opens the checkout page.
Opens WPIDE on
Code
add_action( 'wp_footer', function () {
if ( ! function_exists( 'is_checkout' ) || ! is_checkout() || is_wc_endpoint_url() || ! WC()->cart || WC()->cart->is_empty() ) {
return;
}
$items = array();
foreach ( WC()->cart->get_cart() as $line ) {
$product = $line['data'];
$items[] = array(
'item_id' => $product->get_sku() ? $product->get_sku() : (string) $product->get_id(),
'item_name' => $product->get_name(),
'price' => round( (float) wc_get_price_to_display( $product ), 2 ),
'quantity' => (int) $line['quantity'],
);
}
$data = array(
'currency' => get_woocommerce_currency(),
'value' => round( (float) WC()->cart->get_cart_contents_total() + (float) WC()->cart->get_cart_contents_tax(), 2 ),
'coupon' => implode( ',', WC()->cart->get_applied_coupons() ),
'items' => $items,
);
echo "<script>window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('event', 'begin_checkout', " . wp_json_encode( $data ) . ");</script>\n";
} );
Notes
Needs the GA4 tag (gtag.js) on the page.
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.