Skip to content

Instantly share code, notes, and snippets.

@webzunft
Created April 26, 2024 13:33
Show Gist options
  • Save webzunft/316f6b53c88ff41287c82f940aa710d1 to your computer and use it in GitHub Desktop.
Save webzunft/316f6b53c88ff41287c82f940aa710d1 to your computer and use it in GitHub Desktop.
Track Easy Digital Downloads ecommerce data in self-hosted Matomo
/**
* Tracking order items and orders for Easy Digital Downloads as Ecommerce data in a self-hosted Matomo (the WordPress plugin)
* the code is fired on the purchase confirmation page that appears right after the purchase.
* Based on https://matomo.org/faq/reports/advanced-manually-tracking-ecommerce-actions-in-matomo/
*/
add_action('edd_order_receipt_after_table', function( $order, $edd_receipt_args ) {
if ( empty( $edd_receipt_args['payment_id'] ) ) {
return;
}
// Only accept complete or pending orders. Pending orders can be caused by a delay with PayPal, so we are accepting them here
if ( ! in_array( $order->status, array( 'complete', 'pending' ) ) ) {
return;
}
$payment = edd_get_payment( $order->ID );
// The payment was completed less than 7 days ago – prevents confusing the data with old orders
if ( time() - strtotime( $order->date_completed ) > WEEK_IN_SECONDS ) {
return;
}
$grand_total = edd_get_payment_amount( $order->ID );
$cart = edd_get_payment_meta_cart_details( $order->ID, true );
if ( ! $cart ) {
return;
}
?><script>
var _paq = window._paq = window._paq || [];
<?php
foreach ( $cart as $key => $item ) {
$price_id = edd_get_cart_item_price_id( $item );
$itemname = $item['name'];
if ( ! is_null( $price_id ) ) {
$itemname .= ' - ' . edd_get_price_option_name( $item['id'], $price_id );
}
?>_paq.push(['addEcommerceItem',
'<?php echo esc_js( edd_use_skus() ? edd_get_download_sku( $item['id'] ) : $item['id'] ); ?>', // SKU
'<?php echo esc_js( $itemname ); ?>', // Name
[], // Categories
<?php echo esc_js( $item['item_price'] ); ?>, // Price
1 // Quantity
]);
<?php
}
// Order
?>_paq.push(['trackEcommerceOrder',
"<?php echo esc_js( edd_get_payment_number( $order->ID ) ); ?>", // orderId
<?php echo $grand_total ? esc_js( $grand_total ) : '0'; ?>, // grandTotal (revenue)
<?php echo $grand_total ? esc_js( $grand_total ) : '0'; ?>, // subTotal
<?php echo edd_use_taxes() ? esc_js( edd_get_payment_tax( $order->ID ) ) : '0'; ?>, // tax
0, // shipping
false // discount
]);
</script><?php
}, 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment