Purchase event
function ga4_purchase_event() {
global $wp;
if ( is_wc_endpoint_url( ‘order-received’ ) ) {
$order_id = $wp->query_vars[‘order-received’];
$order = wc_get_order( $order_id );
$total = $order->get_total();
$currency = get_woocommerce_currency();
echo “<script>gtag(‘event’, ‘purchase’, {‘transaction_id:’$order,’value’:’$total’,’currency’:’$currency’});</script>”;
}
}
add_action( ‘woocommerce_thankyou’, ‘ga4_purchase_event’ );
Add to cart
add_action( ‘woocommerce_add_to_cart’, ‘ga4_add_to_cart_event’, 10, 6 );
function ga4_add_to_cart_event( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
// Get the GA4 tracking code
$ga4_tracking_code = ‘GA4-XXXXXXXX-X’;
// Get the product data
$product = wc_get_product( $product_id );
// Send the “add to cart” event to GA4
gtag( ‘event’, ‘add_to_cart’, array(
‘send_to’ => $ga4_tracking_code,
‘event_category’ => ‘Ecommerce’,
‘event_label’ => $product->get_name(),
‘value’ => $product->get_price(),
‘items’ => array(
array(
‘id’ => $product->get_sku(),
‘name’ => $product->get_name(),
‘price’ => $product->get_price(),
‘quantity’ => $quantity,
)
)
) );
}
Initiate checkout
add_action( ‘woocommerce_before_checkout_form’, ‘ga4_begin_checkout_event’ );
function ga4_begin_checkout_event() {
// Get the GA4 tracking code
$ga4_tracking_code = ‘GA4-XXXXXXXX-X’;
// Get the cart contents
$cart = WC()->cart->get_cart();
// Prepare the items array for the begin_checkout event
$items = array();
foreach ( $cart as $cart_item ) {
$product = $cart_item[‘data’];
$items[] = array(
‘id’ => $product->get_sku(),
‘name’ => $product->get_name(),
‘price’ => $product->get_price(),
‘quantity’ => $cart_item[‘quantity’],
);
}
// Send the “begin_checkout” event to GA4
gtag( ‘event’, ‘begin_checkout’, array(
‘send_to’ => $ga_tracking_code,
‘event_category’ => ‘Ecommerce’,
‘items’ => $items,
‘value’ => WC()->cart->total,
‘currency’ => get_woocommerce_currency()
) );
}
View Item
add_action( ‘woocommerce_before_single_product’, ‘ga4_view_item_event’ );
function ga4_view_item_event() {
// Get the GA4 tracking code
$ga4_tracking_code = ‘GA4-XXXXXXXX-X’;
// Get the current product
global $product;
// Send the “view_item” event to GA4
gtag( ‘event’, ‘view_item’, array(
‘send_to’ => $ga4_tracking_code,
‘event_category’ => ‘Ecommerce’,
‘items’ => array(
array(
‘id’ => $product->get_sku(),
‘name’ => $product->get_name(),
‘price’ => $product->get_price(),
‘quantity’ => 1,
)
)
) );
}