From 04fb33a49d601160d28c890ab7f6352f7a2af9ed Mon Sep 17 00:00:00 2001 From: Dan0sz <18595395+Dan0sz@users.noreply.github.com> Date: Sat, 1 Jun 2024 10:31:05 +0200 Subject: [PATCH] Fixed: track AJAX (i.e. non-interactivity API) add to cart events for non-block themes. --- src/Integrations/WooCommerce.php | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/Integrations/WooCommerce.php b/src/Integrations/WooCommerce.php index 3f970064..adef83cc 100644 --- a/src/Integrations/WooCommerce.php +++ b/src/Integrations/WooCommerce.php @@ -21,11 +21,10 @@ class WooCommerce { 'cart_total', 'cart_total_items', 'customer_id', - 'id', - 'name', 'order_id', 'price', 'product_id', + 'product_name', 'quantity', 'shipping', 'subtotal', @@ -76,6 +75,7 @@ private function init( $init ) { */ add_filter( 'woocommerce_after_add_to_cart_form', [ $this, 'track_add_to_cart_on_product_page' ] ); add_filter( 'woocommerce_store_api_validate_add_to_cart', [ $this, 'track_add_to_cart' ], 10, 2 ); + add_filter( 'woocommerce_ajax_added_to_cart', [ $this, 'track_ajax_add_to_cart' ] ); add_action( 'woocommerce_remove_cart_item', [ $this, 'track_remove_cart_item' ], 10, 2 ); add_action( 'wp_head', [ $this, 'track_entered_checkout' ] ); add_action( 'woocommerce_thankyou', [ $this, 'track_purchase' ] ); @@ -146,6 +146,25 @@ public function track_add_to_cart_on_product_page() { } /** + * Track (non-Interactivity API, i.e. AJAX) add to cart events. + * + * @param string|int $product_id ID of the product added to the cart. + * + * @return void + */ + public function track_ajax_add_to_cart( $product_id ) { + $product = wc_get_product( $product_id ); + $add_to_cart_data = [ + 'id' => $product_id, + 'quantity' => $_POST[ 'quantity' ] ?? 1, + ]; + + $this->track_add_to_cart( $product, $add_to_cart_data ); + } + + /** + * Track regular (i.e. interactivity API) add to cart events. + * * @param WC_Product $product General information about the product added to cart. * @param array $add_to_cart_data Cart data for the product added to the cart, e.g. quantity, variation ID, etc. *