Completed
Push — add/8181-enhanced-google-analy... ( 3e3062 )
by
unknown
08:14
created

Jetpack_Google_Analytics_Universal::add_to_cart()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 29
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 13
nc 4
nop 0
dl 0
loc 29
rs 8.5806
c 0
b 0
f 0
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
		// For attaching to a button click on a single product view
26
		add_action( 'woocommerce_after_add_to_cart_button', array( $this, 'add_to_cart' ) );
27
28
		// For attaching to button clicks on multi-product views
29
		add_action( 'wp_footer', array( $this, 'loop_add_to_cart' ) );
30
31
		add_action( 'wp_footer', array( $this, 'wp_footer' ) );
32
	}
33
34
	public function wp_head() {
35
		$tracking_code = Jetpack_Google_Analytics_Options::get_tracking_code();
36
		if ( empty( $tracking_code ) ) {
37
			echo "<!-- No tracking ID configured for Jetpack Google Analytics -->\r\n";
38
			return;
39
		}
40
41
		// If we're in the admin_area, return without inserting code.
42
		if ( is_admin() ) {
43
			return;
44
		}
45
46
		/**
47
		 * Allow for additional elements to be added to the universal Google Analytics queue (ga) array
48
		 *
49
		 * @since 5.6.0
50
		 *
51
		 * @param array $custom_vars Array of universal Google Analytics queue elements
52
		 */
53
		$universal_commands = apply_filters( 'jetpack_wga_universal_commands', array() );
54
55
		$async_code = "
56
			<!-- Jetpack Google Analytics -->
57
			<script>
58
				window.ga = window.ga || function(){ ( ga.q = ga.q || [] ).push( arguments ) }; ga.l=+new Date;
59
				ga( 'create', '%tracking_id%', 'auto' );
60
				ga( 'require', 'ec' );
61
				%universal_commands%
62
			</script>
63
			<script async src='https://www.google-analytics.com/analytics.js'></script>
64
			<!-- End Jetpack Google Analytics -->
65
		";
66
		$async_code = str_replace( '%tracking_id%', $tracking_code, $async_code );
67
68
		$universal_commands_string = implode( "\r\n", $universal_commands );
69
		$async_code = str_replace( '%universal_commands%', $universal_commands_string, $async_code );
70
71
		echo "$async_code\r\n";
72
	}
73
74
	public function maybe_anonymize_ip( $command_array ) {
75
		if ( Jetpack_Google_Analytics_Options::anonymize_ip_is_enabled() ) {
76
			array_push( $command_array, "ga( 'set', 'anonymizeIp', true );" );
77
		}
78
79
		return $command_array;
80
	}
81
82
	public function maybe_track_purchases( $command_array ) {
83
		global $wp;
84
85
		if ( ! Jetpack_Google_Analytics_Options::track_purchases_is_enabled() ) {
86
			return $command_array;
87
		}
88
89
		if ( ! class_exists( 'WooCommerce' ) ) {
90
			return $command_array;
91
		}
92
93
		$minimum_woocommerce_active = class_exists( 'WooCommerce' ) && version_compare( WC_VERSION, '3.0', '>=' );
94
		if ( ! $minimum_woocommerce_active ) {
95
			return $command_array;
96
		}
97
98
		if ( ! is_order_received_page() ) {
99
			return $command_array;
100
		}
101
102
		$order_id = isset( $wp->query_vars['order-received'] ) ? $wp->query_vars['order-received'] : 0;
103
		if ( 0 == $order_id ) {
104
			return $command_array;
105
		}
106
107
		// A 1 indicates we've already tracked this order - don't do it again
108
		if ( 1 == get_post_meta( $order_id, '_ga_tracked', true ) ) {
109
			return $command_array;
110
		}
111
112
		$order = new WC_Order( $order_id );
113
		$order_currency = $order->get_currency();
114
		$command = "ga( 'set', '&cu', '" . esc_js( $order_currency ) . "' );";
115
		array_push( $command_array, $command );
116
117
		// Order items
118
		if ( $order->get_items() ) {
119
			foreach ( $order->get_items() as $item ) {
120
				$product = $order->get_product_from_item( $item );
121
				$sku_or_id = $product->get_sku() ? $product->get_sku() : '#' . $product->get_id();
122
123
				$item_details = array(
124
					'id' => $sku_or_id,
125
					'name' => $item['name'],
126
					'category' => Jetpack_Google_Analytics_Utils::get_product_categories_concatenated( $product ),
127
					'price' => $order->get_item_total( $item ),
128
					'quantity' => $item['qty'],
129
				);
130
				$command = "ga( 'ec:addProduct', " . wp_json_encode( $item_details ) . " );";
131
				array_push( $command_array, $command );
132
			}
133
		}
134
135
		// Order summary
136
		$summary = array(
137
			'id' => $order->get_order_number(),
138
			'affiliation' => get_bloginfo( 'name' ),
139
			'revenue' => $order->get_total(),
140
			'tax' => $order->get_total_tax(),
141
			'shipping' => $order->get_total_shipping()
142
		);
143
		$command = "ga( 'ec:setAction', 'purchase', " . wp_json_encode( $summary ) . " );";
144
		array_push( $command_array, $command );
145
146
		update_post_meta( $order_id, '_ga_tracked', 1 );
147
148
		return $command_array;
149
	}
150
151
	public function add_to_cart() {
152
		if ( ! Jetpack_Google_Analytics_Options::track_add_to_cart_is_enabled() ) {
153
			return;
154
		}
155
156
		if ( ! is_single() ) {
157
			return;
158
		}
159
160
		global $product;
161
162
		$product_sku_or_id = $product->get_sku() ? $product->get_sku() : '#' . $product->get_id();
163
		$selector = ".single_add_to_cart_button";
164
165
		wc_enqueue_js(
166
			"jQuery( function( $ ) {
167
				$( '" . esc_js( $selector ) . "' ).click( function() {
168
					var productDetails = {
169
						'id': '" . esc_js( $product_sku_or_id ) . "',
170
						'name' : '" . esc_js( $product->get_title() ) . "',
171
						'quantity': $( 'input.qty' ).val() ? $( 'input.qty' ).val() : '1',
172
					};
173
					ga( 'ec:addProduct', productDetails );
174
					ga( 'ec:setAction', 'add' );
175
					ga( 'send', 'event', 'UX', 'click', 'add to cart' );
176
				} );
177
			} );"
178
		);
179
	}
180
181
	public function loop_add_to_cart() {
182
		if ( ! Jetpack_Google_Analytics_Options::track_add_to_cart_is_enabled() ) {
183
			return;
184
		}
185
186
		if ( ! class_exists( 'WooCommerce' ) ) {
187
			return;
188
		}
189
190
		$minimum_woocommerce_active = class_exists( 'WooCommerce' ) && version_compare( WC_VERSION, '3.0', '>=' );
191
		if ( ! $minimum_woocommerce_active ) {
192
			return;
193
		}
194
195
		$selector = ".add_to_cart_button:not(.product_type_variable, .product_type_grouped)";
196
197
		wc_enqueue_js(
198
			"jQuery( function( $ ) {
199
				$( '" . esc_js( $selector ) . "' ).click( function() {
200
					var productSku = $( this ).data( 'product_sku' );
201
					var productID = $( this ).data( 'product_id' );
202
					var productDetails = {
203
						'id': productSku ? productSku : '#' + productID,
204
						'quantity': $( this ).data( 'quantity' ),
205
					};
206
					ga( 'ec:addProduct', productDetails );
207
					ga( 'ec:setAction', 'add' );
208
					ga( 'send', 'event', 'UX', 'click', 'add to cart' );
209
				} );
210
			} );"
211
		);
212
	}
213
214
	public function wp_footer() {
215
		if ( ! Jetpack_Google_Analytics_Options::has_tracking_code() ) {
216
			return;
217
		}
218
219
		if ( is_admin() ) {
220
			return;
221
		}
222
223
		$async_code = "
224
			<!-- Jetpack Google Analytics -->
225
			<script>
226
				ga( 'send', 'pageview' );
227
			</script>
228
			<!-- End Jetpack Google Analytics -->
229
		";
230
231
		echo "$async_code\r\n";
232
	}
233
}