From c6b1c11873ae42c6c79ce26e761ac421423aa646 Mon Sep 17 00:00:00 2001 From: Dan0sz <18595395+Dan0sz@users.noreply.github.com> Date: Thu, 18 Jul 2024 21:52:31 +0200 Subject: [PATCH] Fixed: Woo Add To Cart event wasn't sent on product pages. --- src/Integrations/WooCommerce.php | 42 ++++++++++++++++++++++++-------- 1 file changed, 32 insertions(+), 10 deletions(-) diff --git a/src/Integrations/WooCommerce.php b/src/Integrations/WooCommerce.php index 2c7fb86..91e47dd 100644 --- a/src/Integrations/WooCommerce.php +++ b/src/Integrations/WooCommerce.php @@ -78,7 +78,8 @@ private function init( $init ) { /** * Trigger tracking events. */ - add_filter( 'woocommerce_after_add_to_cart_form', [ $this, 'track_add_to_cart_on_product_page' ] ); + add_action( 'woocommerce_before_add_to_cart_quantity', [ $this, 'add_cart_form_hidden_input' ] ); + add_action( '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 ); @@ -129,8 +130,29 @@ public function add_http_referer( $add_to_cart_data, $request ) { } /** - * A hacky approach (with lack of a proper solution) to make sure Add To Cart events are tracked on simple product pages. Unfortunately, cart - * information isn't available this way. + * Adds a hidden input with the same name and value as the add-to-cart button. + * + * TODO: This hack can be removed when the JS library uses sendBeacon to send the event. + * + * @return void + * + * @codeCoverageIgnore Because we can't test JS here. + */ + public function add_cart_form_hidden_input() { + $product = wc_get_product(); + + if ( ! $product ) { + return; + } + ?> + +