diff --git a/assets/js/src/utils/index.js b/assets/js/src/utils/index.js index 04e2aea0..dc314b00 100644 --- a/assets/js/src/utils/index.js +++ b/assets/js/src/utils/index.js @@ -15,7 +15,7 @@ export const getProductFieldObject = ( product, quantity ) => { variantData.item_variant = product.variation; } - return { + const data = { item_id: getProductId( product ), item_name: product.name, ...getProductCategories( product ), @@ -26,6 +26,21 @@ export const getProductFieldObject = ( product, quantity ) => { ), ...variantData, }; + + // Apply discounts to ecommerce events. + // https://developers.google.com/analytics/devguides/collection/ga4/apply-discount?client_type=gtag + if ( product?.price_after_coupon_discount < product.prices.price ) { + data.discount = formatPrice( + product.prices.price - product.price_after_coupon_discount, + product.prices.currency_minor_unit + ); + data.price = formatPrice( + product.price_after_coupon_discount, + product.prices.currency_minor_unit + ); + } + + return data; }; /** diff --git a/includes/class-wc-abstract-google-analytics-js.php b/includes/class-wc-abstract-google-analytics-js.php index c5dcad66..38844cf7 100644 --- a/includes/class-wc-abstract-google-analytics-js.php +++ b/includes/class-wc-abstract-google-analytics-js.php @@ -288,7 +288,10 @@ function ( $item ) { return array_merge( $this->get_formatted_product( $item->get_product() ), array( - 'quantity' => $item->get_quantity(), + 'quantity' => $item->get_quantity(), + // The method get_total() will return the price after coupon discounts. + // https://github.com/woocommerce/woocommerce/blob/54eba223b8dec015c91a13423f9eced09e96f399/plugins/woocommerce/includes/class-wc-order-item-product.php#L308-L310 + 'price_after_coupon_discount' => $this->get_formatted_price( $item->get_total() ), ) ); },