To add a function where a Google Analytics 4 purchase event is implemented on the “Thank You” page in WooCommerce for WordPress, you can use the following steps:
- Install the Google Analytics for WordPress plugin, which allows you to easily add GA4 tracking code to your website.
- Create a GA4 property and get the tracking code from the GA4 admin.
- Add the GA4 tracking code to your website using the Google Analytics for WordPress plugin.
- Create a custom function in your theme’s functions.php file that fires the GA4 purchase event when the “Thank You” page is loaded.
- In this function, use the JavaScript
gtag('event', 'purchase', {'value':'[value]','currency':'[currency]'});
command to fire the purchase event and pass in the transaction value and currency. - Add the function to the “Thank You” page using the WooCommerce
woocommerce_thankyou
action hook.
example
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>”;
}
}
Next, you need to add the function to the “Thank You” page using the WooCommerce woocommerce_thankyou
action hook like this:
add_action( ‘woocommerce_thankyou’, ‘ga4_purchase_event’ );