Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add Rounded Sale Event
/*
* Since Google Analytics only allows integers as event values, Monster Insights multiplies the value by 100.
* This makes it difficult to use sale events for goal tracking and adding their values to other goals.
* This function adds a custom event with the sales value rounded, which should be close enough in most cases.
*
* Requires WooCommerce (version >= 3.0) and Monster Insights (free or premium) to be active.
*/
add_filter( 'monsterinsights_mp_api_call', 'gbol_add_rounded_sale_event' );
function gbol_add_rounded_sale_event( $body ) {
// If this is an add order event and we have the payment ID
if ( ! empty( $body['ea'] ) && $body['ea'] === 'Completed Checkout' && ! empty( $body['el'] ) ) {
$payment_id = (int) $body['el'];
$order = wc_get_order( $payment_id );
$total = round( $order->get_total() );
$args = array(
't' => 'event', // Required: Change the default type to event
'ec' => 'Rounded Sale', // Required: Event Category
'ea' => 'New Sale', // Required: Event Action
'el' => $payment_id, // Required: Event Label
'ev' => $total, // Required: Event Value, Rounded
'cid' => ! empty( $body['cid'] ) ? $body['cid'] : null, // Required: Google Client ID
);
if ( ! empty( $body['uid'] ) ) {
$args['uid'] = $body['uid']; // UserID tracking
}
monsterinsights_mp_track_event_call( $args );
}
return $body;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment