Completed
Push — update/pre_connection_jitms_pl... ( 9bf136...a14e59 )
by
unknown
214:58 queued 207:06
created

Jetpack_Google_AMP_Analytics::amp_send_ga_events()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 0
dl 0
loc 34
rs 9.376
c 0
b 0
f 0
1
<?php
2
/**
3
 * Add support for Google Analytics e-commerce events for AMP pages.
4
 *
5
 * @package Jetpack
6
 */
7
8
/**
9
 * Bail if accessed directly
10
 */
11
if ( ! defined( 'ABSPATH' ) ) {
12
	exit;
13
}
14
15
/**
16
 * Jetpack_Google_AMP_Analytics class.
17
 */
18
class Jetpack_Google_AMP_Analytics {
19
	/**
20
	 * Constructor method.
21
	 */
22
	public function __construct() {
23
		$this->maybe_load_hooks();
24
	}
25
26
	/**
27
	 * Maybe load the hooks.
28
	 * Checks if its AMP request, if WooCommerce is available, if there's tracking code and in tracking is enabled.
29
	 */
30
	public function maybe_load_hooks() {
31
		if ( ! class_exists( 'Jetpack_AMP_Support' ) || ! Jetpack_AMP_Support::is_amp_request() ) {
32
			return;
33
		}
34
35
		if ( ! class_exists( 'WooCommerce' ) ) {
36
			return;
37
		}
38
39
		if ( ! Jetpack_Google_Analytics_Options::has_tracking_code() ) {
40
			return;
41
		}
42
43
		if ( ! Jetpack_Google_Analytics_Options::track_add_to_cart_is_enabled() ) {
44
			return;
45
		}
46
47
		add_action( 'woocommerce_add_to_cart', array( $this, 'amp_add_to_cart' ), 10, 6 );
48
		add_action( 'woocommerce_thankyou', array( $this, 'amp_after_purchase' ), 10, 1 );
49
		add_action( 'wp_footer', array( $this, 'amp_send_ga_events' ) );
50
	}
51
52
	/**
53
	 * Generate a GA event when adding an item to the cart.
54
	 *
55
	 * @param string $cart_item_key Cart item key.
56
	 * @param string $product_id Product ID.
57
	 * @param int    $quantity Product quantity.
58
	 * @param int    $variation_id Product variation ID.
59
	 * @param object $variation Product variation.
60
	 * @param object $cart_item_data Cart item data.
61
	 */
62
	public function amp_add_to_cart( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
63
		$product = wc_get_product( $product_id );
64
		if ( $product ) {
65
			$product_sku  = Jetpack_Google_Analytics_Utils::get_product_sku_or_id( $product );
66
			$product_name = $product->get_name();
67
68
			$events   = WC()->session->get( 'wc_ga_events' );
69
			$events[] = array(
70
				'type'      => 'add',
71
				'ga_params' => array(
72
					'pa'    => 'add',
73
					'pr1id' => sanitize_text_field( $product_sku ),
74
					'pr1nm' => sanitize_text_field( $product_name ),
75
					'pr1qt' => absint( $quantity ),
76
				),
77
			);
78
			WC()->session->set( 'wc_ga_events', $events );
79
		}
80
	}
81
82
	/**
83
	 * Generate a GA event when removing an item to the cart.
84
	 *
85
	 * @param int $order_id The Order ID.
86
	 */
87
	public function amp_after_purchase( $order_id ) {
88
		$events      = WC()->session->get( 'wc_ga_events' );
89
		$order       = wc_get_order( $order_id );
90
		$order_total = $order->get_total();
91
		$order_tax   = $order->get_total_tax();
92
93
		$i     = 1;
94
		$event = array(
95
			'type'      => 'purchase',
96
			'ga_params' => array(
97
				'pa' => 'purchase',
98
				'ti' => absint( $order_id ),
99
				'tr' => (float) $order_total,
100
				'tt' => (float) $order_tax,
101
			),
102
		);
103
		foreach ( $order->get_items() as $item_id => $item ) {
104
			$product = $item->get_product();
105
			if ( $product ) {
106
				$event['ga_params'][ 'pr' . $i . 'id' ] = sanitize_text_field( Jetpack_Google_Analytics_Utils::get_product_sku_or_id( $product ) );
107
				$event['ga_params'][ 'pr' . $i . 'nm' ] = sanitize_text_field( $item->get_name() );
108
				$event['ga_params'][ 'pr' . $i . 'qt' ] = absint( $item->get_quantity() );
109
				$i++;
110
			}
111
		}
112
113
		$events[] = $event;
114
		WC()->session->set( 'wc_ga_events', $events );
115
	}
116
117
	/**
118
	 * Send the stored events to GA.
119
	 */
120
	public function amp_send_ga_events() {
121
		if ( 'GET' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
122
			return;
123
		}
124
125
		$events = WC()->session->get( 'wc_ga_events' );
126
		if ( ! is_array( $events ) ) {
127
			return;
128
		}
129
130
		foreach ( $events as $i => $event ) {
131
			?>
132
			<amp-analytics type='googleanalytics'>
133
				<script type='application/json'>
134
				{
135
					"vars": {
136
						"account": "<?php echo esc_html( Jetpack_Google_Analytics_Options::get_tracking_code() ); ?>"
137
					},
138
					"triggers": {
139
						"trackPageview": {
140
							"on": "visible",
141
							"request": "pageview",
142
							"extraUrlParams": <?php echo wp_json_encode( $event['ga_params'] ); ?>
143
						}
144
					}
145
				}
146
				</script>
147
			</amp-analytics>
148
			<?php
149
150
			array_shift( $events );
151
		}
152
		WC()->session->set( 'wc_ga_events', $events );
153
	}
154
}
155