From 1c5010de01cf421326a4403d62fa870da0c8dcb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomek=20Wytr=C4=99bowicz?= Date: Tue, 10 Oct 2023 19:26:45 +0200 Subject: [PATCH] DRY JS construction in `WC_Google_Gtag_JS::listing_click` --- includes/class-wc-google-gtag-js.php | 48 ++++++++++++---------------- 1 file changed, 20 insertions(+), 28 deletions(-) diff --git a/includes/class-wc-google-gtag-js.php b/includes/class-wc-google-gtag-js.php index 3322e7e1..9c1b5a19 100644 --- a/includes/class-wc-google-gtag-js.php +++ b/includes/class-wc-google-gtag-js.php @@ -199,36 +199,28 @@ public static function listing_impression( $product ) { * @param WC_Product $product */ public static function listing_click( $product ) { - $item = array( - 'id' => self::get_product_identifier( $product ), - 'name' => $product->get_title(), - 'category' => self::product_get_category_line( $product ), - 'quantity' => 1, - ); - - $select_content_event_code = self::get_event_code( - 'select_content', - array( - 'items' => array( $item ), - ) - ); - - $add_to_cart_event_code = self::get_event_code( - 'add_to_cart', - array( - 'items' => array( $item ), - ) - ); + $items = [ + 'items' => [ + 'id' => self::get_product_identifier( $product ), + 'name' => $product->get_title(), + 'category' => self::product_get_category_line( $product ), + 'quantity' => 1, + ] + ]; wc_enqueue_js( - " - $( '.product.post-" . esc_js( $product->get_id() ) . ' a , .product.post-' . esc_js( $product->get_id() ) . " button' ).on('click', function() { - if ( false === $(this).hasClass( 'product_type_variable' ) && false === $(this).hasClass( 'product_type_grouped' ) ) { - $add_to_cart_event_code - } else { - $select_content_event_code - } - });" + sprintf( + "$( '.product.post-%s a , .product.post-%1\$s button' ).on('click', function() { + if ( false === $(this).hasClass( 'product_type_variable' ) && false === $(this).hasClass( 'product_type_grouped' ) ) { + %s + } else { + %s + } + });", + esc_js( $product->get_id() ), + self::get_event_code( 'add_to_cart', $items ), + self::get_event_code( 'select_content', $items ), + ) ); }