PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 7.2.2
Jetpack – WP Security, Backup, Speed, & Growth v7.2.2
16.2 16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 All 502 releases
jetpack / modules / google-analytics / classes / wp-google-analytics-universal.php

wp-google-analytics-universal.php in Jetpack – WP Security, Backup, Speed, & Growth 7.2.2, at modules/google-analytics/classes/wp-google-analytics-universal.php

411 lines 12.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /**
4 * Jetpack_Google_Analytics_Universal hooks and and enqueues support for analytics.js
5 * https://developers.google.com/analytics/devguides/collection/analyticsjs/
6 * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce
7 *
8 * @author allendav
9 */
10
11 /**
12 * Bail if accessed directly
13 */
14 if ( ! defined( 'ABSPATH' ) ) {
15 exit;
16 }
17
18 class Jetpack_Google_Analytics_Universal {
19 public function __construct() {
20 add_filter( 'jetpack_wga_universal_commands', array( $this, 'maybe_anonymize_ip' ) );
21 add_filter( 'jetpack_wga_universal_commands', array( $this, 'maybe_track_purchases' ) );
22
23 add_action( 'wp_head', array( $this, 'wp_head' ), 999999 );
24
25 add_action( 'woocommerce_after_add_to_cart_button', array( $this, 'add_to_cart' ) );
26 add_action( 'wp_footer', array( $this, 'loop_add_to_cart' ) );
27 add_action( 'woocommerce_after_cart', array( $this, 'remove_from_cart' ) );
28 add_action( 'woocommerce_after_mini_cart', array( $this, 'remove_from_cart' ) );
29 add_filter( 'woocommerce_cart_item_remove_link', array( $this, 'remove_from_cart_attributes' ), 10, 2 );
30 add_action( 'woocommerce_after_shop_loop_item', array( $this, 'listing_impression' ) );
31 add_action( 'woocommerce_after_shop_loop_item', array( $this, 'listing_click' ) );
32 add_action( 'woocommerce_after_single_product', array( $this, 'product_detail' ) );
33 add_action( 'woocommerce_after_checkout_form', array( $this, 'checkout_process' ) );
34
35 // we need to send a pageview command last - so we use priority 24 to add
36 // this command's JavaScript just before wc_print_js is called (pri 25)
37 add_action( 'wp_footer', array( $this, 'send_pageview_in_footer' ), 24 );
38 }
39
40 public function wp_head() {
41 $tracking_code = Jetpack_Google_Analytics_Options::get_tracking_code();
42 if ( empty( $tracking_code ) ) {
43 echo "<!-- No tracking ID configured for Jetpack Google Analytics -->\r\n";
44 return;
45 }
46
47 // If we're in the admin_area, return without inserting code.
48 if ( is_admin() ) {
49 return;
50 }
51
52 /**
53 * Allow for additional elements to be added to the universal Google Analytics queue (ga) array
54 *
55 * @since 5.6.0
56 *
57 * @param array $custom_vars Array of universal Google Analytics queue elements
58 */
59 $universal_commands = apply_filters( 'jetpack_wga_universal_commands', array() );
60
61 $async_code = "
62 <!-- Jetpack Google Analytics -->
63 <script>
64 window.ga = window.ga || function(){ ( ga.q = ga.q || [] ).push( arguments ) }; ga.l=+new Date;
65 ga( 'create', '%tracking_id%', 'auto' );
66 ga( 'require', 'ec' );
67 %universal_commands%
68 </script>
69 <script async src='https://www.google-analytics.com/analytics.js'></script>
70 <!-- End Jetpack Google Analytics -->
71 ";
72 $async_code = str_replace( '%tracking_id%', $tracking_code, $async_code );
73
74 $universal_commands_string = implode( "\r\n", $universal_commands );
75 $async_code = str_replace( '%universal_commands%', $universal_commands_string, $async_code );
76
77 echo "$async_code\r\n";
78 }
79
80 public function maybe_anonymize_ip( $command_array ) {
81 if ( Jetpack_Google_Analytics_Options::anonymize_ip_is_enabled() ) {
82 array_push( $command_array, "ga( 'set', 'anonymizeIp', true );" );
83 }
84
85 return $command_array;
86 }
87
88 public function maybe_track_purchases( $command_array ) {
89 global $wp;
90
91 if ( ! Jetpack_Google_Analytics_Options::track_purchases_is_enabled() ) {
92 return $command_array;
93 }
94
95 if ( ! class_exists( 'WooCommerce' ) ) {
96 return $command_array;
97 }
98
99 $minimum_woocommerce_active = class_exists( 'WooCommerce' ) && version_compare( WC_VERSION, '3.0', '>=' );
100 if ( ! $minimum_woocommerce_active ) {
101 return $command_array;
102 }
103
104 if ( ! is_order_received_page() ) {
105 return $command_array;
106 }
107
108 $order_id = isset( $wp->query_vars['order-received'] ) ? $wp->query_vars['order-received'] : 0;
109 if ( 0 == $order_id ) {
110 return $command_array;
111 }
112
113 // A 1 indicates we've already tracked this order - don't do it again
114 if ( 1 == get_post_meta( $order_id, '_ga_tracked', true ) ) {
115 return $command_array;
116 }
117
118 $order = new WC_Order( $order_id );
119 $order_currency = $order->get_currency();
120 $command = "ga( 'set', '&cu', '" . esc_js( $order_currency ) . "' );";
121 array_push( $command_array, $command );
122
123 // Order items
124 if ( $order->get_items() ) {
125 foreach ( $order->get_items() as $item ) {
126 $product = $order->get_product_from_item( $item );
127 $product_sku_or_id = Jetpack_Google_Analytics_Utils::get_product_sku_or_id( $product );
128
129 $item_details = array(
130 'id' => $product_sku_or_id,
131 'name' => $item['name'],
132 'category' => Jetpack_Google_Analytics_Utils::get_product_categories_concatenated( $product ),
133 'price' => $order->get_item_total( $item ),
134 'quantity' => $item['qty'],
135 );
136 $command = "ga( 'ec:addProduct', " . wp_json_encode( $item_details ) . " );";
137 array_push( $command_array, $command );
138 }
139 }
140
141 // Order summary
142 $summary = array(
143 'id' => $order->get_order_number(),
144 'affiliation' => get_bloginfo( 'name' ),
145 'revenue' => $order->get_total(),
146 'tax' => $order->get_total_tax(),
147 'shipping' => $order->get_total_shipping()
148 );
149 $command = "ga( 'ec:setAction', 'purchase', " . wp_json_encode( $summary ) . " );";
150 array_push( $command_array, $command );
151
152 update_post_meta( $order_id, '_ga_tracked', 1 );
153
154 return $command_array;
155 }
156
157 public function add_to_cart() {
158 if ( ! Jetpack_Google_Analytics_Options::track_add_to_cart_is_enabled() ) {
159 return;
160 }
161
162 if ( ! is_single() ) {
163 return;
164 }
165
166 global $product;
167
168 $product_sku_or_id = Jetpack_Google_Analytics_Utils::get_product_sku_or_id( $product );
169 $selector = ".single_add_to_cart_button";
170
171 wc_enqueue_js(
172 "$( '" . esc_js( $selector ) . "' ).click( function() {
173 var productDetails = {
174 'id': '" . esc_js( $product_sku_or_id ) . "',
175 'name' : '" . esc_js( $product->get_title() ) . "',
176 'quantity': $( 'input.qty' ).val() ? $( 'input.qty' ).val() : '1',
177 };
178 ga( 'ec:addProduct', productDetails );
179 ga( 'ec:setAction', 'add' );
180 ga( 'send', 'event', 'UX', 'click', 'add to cart' );
181 } );"
182 );
183 }
184
185 public function loop_add_to_cart() {
186 if ( ! Jetpack_Google_Analytics_Options::track_add_to_cart_is_enabled() ) {
187 return;
188 }
189
190 if ( ! class_exists( 'WooCommerce' ) ) {
191 return;
192 }
193
194 $minimum_woocommerce_active = class_exists( 'WooCommerce' ) && version_compare( WC_VERSION, '3.0', '>=' );
195 if ( ! $minimum_woocommerce_active ) {
196 return;
197 }
198
199 $selector = ".add_to_cart_button:not(.product_type_variable, .product_type_grouped)";
200
201 wc_enqueue_js(
202 "$( '" . esc_js( $selector ) . "' ).click( function() {
203 var productSku = $( this ).data( 'product_sku' );
204 var productID = $( this ).data( 'product_id' );
205 var productDetails = {
206 'id': productSku ? productSku : '#' + productID,
207 'quantity': $( this ).data( 'quantity' ),
208 };
209 ga( 'ec:addProduct', productDetails );
210 ga( 'ec:setAction', 'add' );
211 ga( 'send', 'event', 'UX', 'click', 'add to cart' );
212 } );"
213 );
214 }
215
216 public function remove_from_cart() {
217 if ( ! Jetpack_Google_Analytics_Options::enhanced_ecommerce_tracking_is_enabled() ) {
218 return;
219 }
220
221 if ( ! Jetpack_Google_Analytics_Options::track_remove_from_cart_is_enabled() ) {
222 return;
223 }
224
225 // We listen at div.woocommerce because the cart 'form' contents get forcibly
226 // updated and subsequent removals from cart would then not have this click
227 // handler attached
228 wc_enqueue_js(
229 "$( 'div.woocommerce' ).on( 'click', 'a.remove', function() {
230 var productSku = $( this ).data( 'product_sku' );
231 var productID = $( this ).data( 'product_id' );
232 var quantity = $( this ).parent().parent().find( '.qty' ).val()
233 var productDetails = {
234 'id': productSku ? productSku : '#' + productID,
235 'quantity': quantity ? quantity : '1',
236 };
237 ga( 'ec:addProduct', productDetails );
238 ga( 'ec:setAction', 'remove' );
239 ga( 'send', 'event', 'UX', 'click', 'remove from cart' );
240 } );"
241 );
242 }
243
244 /**
245 * Adds the product ID and SKU to the remove product link (for use by remove_from_cart above) if not present
246 *
247 * @param string $url Full HTML a tag of the link to remove an item from the cart.
248 * @param string $key Unique Key ID for a cart item.
249 */
250 public function remove_from_cart_attributes( $url, $key ) {
251 if ( false !== strpos( $url, 'data-product_id' ) ) {
252 return $url;
253 }
254
255 $item = WC()->cart->get_cart_item( $key );
256 $product = $item['data'];
257
258 $new_attributes = sprintf(
259 '" data-product_id="%1$s" data-product_sku="%2$s">',
260 esc_attr( $product->get_id() ),
261 esc_attr( $product->get_sku() )
262 );
263
264 $url = str_replace( '">', $new_attributes, $url );
265 return $url;
266 }
267
268 public function listing_impression() {
269 if ( ! Jetpack_Google_Analytics_Options::enhanced_ecommerce_tracking_is_enabled() ) {
270 return;
271 }
272
273 if ( ! Jetpack_Google_Analytics_Options::track_product_impressions_is_enabled() ) {
274 return;
275 }
276
277 if ( isset( $_GET['s'] ) ) {
278 $list = "Search Results";
279 } else {
280 $list = "Product List";
281 }
282
283 global $product, $woocommerce_loop;
284 $product_sku_or_id = Jetpack_Google_Analytics_Utils::get_product_sku_or_id( $product );
285
286 $item_details = array(
287 'id' => $product_sku_or_id,
288 'name' => $product->get_title(),
289 'category' => Jetpack_Google_Analytics_Utils::get_product_categories_concatenated( $product ),
290 'list' => $list,
291 'position' => $woocommerce_loop['loop']
292 );
293 wc_enqueue_js( "ga( 'ec:addImpression', " . wp_json_encode( $item_details ) . " );" );
294 }
295
296 public function listing_click() {
297 if ( ! Jetpack_Google_Analytics_Options::enhanced_ecommerce_tracking_is_enabled() ) {
298 return;
299 }
300
301 if ( ! Jetpack_Google_Analytics_Options::track_product_clicks_is_enabled() ) {
302 return;
303 }
304
305 if ( isset( $_GET['s'] ) ) {
306 $list = "Search Results";
307 } else {
308 $list = "Product List";
309 }
310
311 global $product, $woocommerce_loop;
312 $product_sku_or_id = Jetpack_Google_Analytics_Utils::get_product_sku_or_id( $product );
313
314 $selector = ".products .post-" . esc_js( $product->get_id() ) . " a";
315
316 $item_details = array(
317 'id' => $product_sku_or_id,
318 'name' => $product->get_title(),
319 'category' => Jetpack_Google_Analytics_Utils::get_product_categories_concatenated( $product ),
320 'position' => $woocommerce_loop['loop']
321 );
322
323 wc_enqueue_js(
324 "$( '" . esc_js( $selector ) . "' ).click( function() {
325 if ( true === $( this ).hasClass( 'add_to_cart_button' ) ) {
326 return;
327 }
328
329 ga( 'ec:addProduct', " . wp_json_encode( $item_details ) . " );
330 ga( 'ec:setAction', 'click', { list: '" . esc_js( $list ) . "' } );
331 ga( 'send', 'event', 'UX', 'click', { list: '" . esc_js( $list ) . "' } );
332 } );"
333 );
334 }
335
336 public function product_detail() {
337 if ( ! Jetpack_Google_Analytics_Options::enhanced_ecommerce_tracking_is_enabled() ) {
338 return;
339 }
340
341 if ( ! Jetpack_Google_Analytics_Options::track_product_detail_view_is_enabled() ) {
342 return;
343 }
344
345 global $product;
346 $product_sku_or_id = Jetpack_Google_Analytics_Utils::get_product_sku_or_id( $product );
347
348 $item_details = array(
349 'id' => $product_sku_or_id,
350 'name' => $product->get_title(),
351 'category' => Jetpack_Google_Analytics_Utils::get_product_categories_concatenated( $product ),
352 'price' => $product->get_price()
353 );
354 wc_enqueue_js(
355 "ga( 'ec:addProduct', " . wp_json_encode( $item_details ) . " );" .
356 "ga( 'ec:setAction', 'detail' );"
357 );
358 }
359
360 public function checkout_process() {
361 if ( ! Jetpack_Google_Analytics_Options::enhanced_ecommerce_tracking_is_enabled() ) {
362 return;
363 }
364
365 if ( ! Jetpack_Google_Analytics_Options::track_checkout_started_is_enabled() ) {
366 return;
367 }
368
369 $universal_commands = array();
370 $cart = WC()->cart->get_cart();
371
372 foreach ( $cart as $cart_item_key => $cart_item ) {
373 /**
374 * This filter is already documented in woocommerce/templates/cart/cart.php
375 */
376 $product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
377 $product_sku_or_id = Jetpack_Google_Analytics_Utils::get_product_sku_or_id( $product );
378
379 $item_details = array(
380 'id' => $product_sku_or_id,
381 'name' => $product->get_title(),
382 'category' => Jetpack_Google_Analytics_Utils::get_product_categories_concatenated( $product ),
383 'price' => $product->get_price(),
384 'quantity' => $cart_item[ 'quantity' ]
385 );
386
387 array_push( $universal_commands, "ga( 'ec:addProduct', " . wp_json_encode( $item_details ) . " );" );
388 }
389
390 array_push( $universal_commands, "ga( 'ec:setAction','checkout' );" );
391
392 wc_enqueue_js( implode( "\r\n", $universal_commands ) );
393 }
394
395 public function send_pageview_in_footer() {
396 if ( ! Jetpack_Google_Analytics_Options::has_tracking_code() ) {
397 return;
398 }
399
400 if ( is_admin() ) {
401 return;
402 }
403
404 if ( ! class_exists( 'WooCommerce' ) ) {
405 return;
406 }
407
408 wc_enqueue_js( "ga( 'send', 'pageview' );" );
409 }
410 }
411