-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy pathwoocommerce.php
More file actions
executable file
·1676 lines (1392 loc) · 60.3 KB
/
woocommerce.php
File metadata and controls
executable file
·1676 lines (1392 loc) · 60.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* GTM4WP WooCoommerce integration.
*
* @package GTM4WP
* @author Thomas Geiger
* @copyright 2013- Geiger Tamás e.v. (Thomas Geiger s.e.)
* @license GNU General Public License, version 3
*/
define( 'GTM4WP_WPFILTER_EEC_PRODUCT_ARRAY', 'gtm4wp_eec_product_array' );
define( 'GTM4WP_WPFILTER_EEC_CART_ITEM', 'gtm4wp_eec_cart_item' );
define( 'GTM4WP_WPFILTER_EEC_ORDER_ITEM', 'gtm4wp_eec_order_item' );
define( 'GTM4WP_WPFILTER_EEC_ORDER_DATA', 'gtm4wp_eec_order_data' );
define( 'GTM4WP_WPFILTER_ECC_PURCHASE_DATALAYER', 'gtm4wp_purchase_datalayer' );
define( 'GTM4WP_WPFILTER_EEC_DATALAYER_PAGELOAD', 'gtm4wp_woocommerce_datalayer_on_pageload' );
require_once dirname( __FILE__ ) . '/ecommerce-generic.php';
$gtm4wp_product_counter = 0;
$gtm4wp_last_widget_title = 'Sidebar Products';
$GLOBALS['gtm4wp_grouped_product_ix'] = 1;
$GLOBALS['gtm4wp_woocommerce_purchase_data_pushed'] = false;
/**
* Function to be called on the gtm4wp_add_global_vars_array hook to output WooCommerce related global JavaScript variables.
*
* @param array $return The already added variables as key-value pairs in an associative array.
* @return array The $return parameter with added global JavaScript variables as key-value pairs.
*/
function gtm4wp_woocommerce_add_global_vars( $return ) {
global $gtm4wp_options;
$return['gtm4wp_use_sku_instead'] = (int) ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCUSESKU ] );
$return['gtm4wp_currency'] = get_woocommerce_currency();
$return['gtm4wp_product_per_impression'] = (int) ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCPRODPERIMPRESSION ] );
$return['gtm4wp_clear_ecommerce'] = (bool) ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCCLEARECOMMERCEDL ] );
$return['gtm4wp_datalayer_max_timeout'] = (int) ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCDLMAXTIMEOUT ] );
$return['gtm4wp_blocks_add_to_cart'] = (bool) ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKECOMMERCE ] && $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCBLOCKSADDTOCART ] );
$return['gtm4wp_rest_root'] = esc_url_raw( get_rest_url() );
$return['gtm4wp_blocks_ajax_url'] = esc_url_raw( admin_url( 'admin-ajax.php' ) );
$return['gtm4wp_blocks_product_nonce'] = wp_create_nonce( 'gtm4wp-product-data' );
$return['gtm4wp_blocks_dedupe_window'] = (int) apply_filters( 'gtm4wp_blocks_dedupe_window', 800 );
$return['gtm4wp_rest_nonce'] = wp_create_nonce( 'wp_rest' );
return $return;
}
/**
* Given a WP_Product instane, this function returns an array of product attributes in the format of
* Google Analytics enhanced ecommerce product data.
*
* @see https://developers.google.com/analytics/devguides/collection/ua/gtm/enhanced-ecommerce
*
* @param WP_Product $product An instance of WP_Product that needs to be transformed into an enhanced ecommerce product object.
* @param array $additional_product_attributes Any key-value pair that needs to be added into the enhanced ecommerce product object.
* @param string $attributes_used_for The placement ID of the product that is passed to the apply_filters hook so that 3rd party code can be notified where this product data is being used.
* @return array|false The enhanced ecommerce product object of the WooCommerce product, or false if the product does not exist.
*/
function gtm4wp_woocommerce_process_product( $product, $additional_product_attributes, $attributes_used_for ) {
global $gtm4wp_options;
if ( ! $product ) {
return false;
}
if ( ! ( $product instanceof WC_Product ) ) {
return false;
}
$product_id = $product->get_id();
$product_type = $product->get_type();
$remarketing_id = $product_id;
$product_sku = $product->get_sku();
if ( 'variation' === $product_type ) {
$parent_product_id = $product->get_parent_id();
$product_cat = gtm4wp_get_product_category( $parent_product_id, $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCUSEFULLCATEGORYPATH ] );
} else {
$product_cat = gtm4wp_get_product_category( $product_id, $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCUSEFULLCATEGORYPATH ] );
}
$product_cat_parts = explode( '/', $product_cat );
if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCUSESKU ] && ( '' !== $product_sku ) ) {
$remarketing_id = $product_sku;
}
$_temp_productdata = array(
'internal_id' => $product_id,
'item_id' => $remarketing_id,
'item_name' => $product->get_title(),
'sku' => $product_sku ? $product_sku : $product_id,
'price' => round( (float) wc_get_price_to_display( $product ), 2 ), // Unfortunately this does not force a .00 postfix for integers.
'stocklevel' => $product->get_stock_quantity(),
'stockstatus' => $product->get_stock_status(),
'google_business_vertical' => $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCBUSINESSVERTICAL ],
);
if ( 'variation' === $product_type ) {
$parent_product = wc_get_product( $parent_product_id );
$parent_item_id = '';
if ( $parent_product instanceof WC_Product && $parent_product->get_sku() ) {
$parent_item_id = $parent_product->get_sku();
}
$_temp_productdata['item_group_sku'] = $parent_item_id;
if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCUSESKU ] && '' !== $parent_item_id ) {
$_temp_productdata['item_group_id'] = $parent_item_id;
} else {
$_temp_productdata['item_group_id'] = $parent_product_id;
}
}
if ( 1 === count( $product_cat_parts ) ) {
$_temp_productdata['item_category'] = $product_cat_parts[0];
} elseif ( count( $product_cat_parts ) > 1 ) {
$_temp_productdata['item_category'] = $product_cat_parts[0];
$max_category_levels = min( 5, count( $product_cat_parts ) );
for ( $i = 1; $i < $max_category_levels; $i++ ) {
$_temp_productdata[ 'item_category' . ( $i + 1 ) ] = $product_cat_parts[ $i ];
}
}
$_temp_productdata[ gtm4wp_get_gads_product_id_variable_name( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCBUSINESSVERTICAL ] ) ] = gtm4wp_prefix_productid( $_temp_productdata['item_id'], $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMPRODIDPREFIX ] );
if ( '' !== $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEECBRANDTAXONOMY ] ) {
if ( isset( $parent_product_id ) && ( 0 !== $parent_product_id ) ) {
$product_id_to_query = $parent_product_id;
} else {
$product_id_to_query = $product_id;
}
$_temp_productdata['item_brand'] = gtm4wp_get_product_term( $product_id_to_query, $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEECBRANDTAXONOMY ] );
}
if ( 'variation' === $product_type ) {
$_temp_productdata['item_variant'] = implode( ',', $product->get_variation_attributes() );
}
$_temp_productdata = array_merge( $_temp_productdata, $additional_product_attributes );
/**
* Filters the ecommerce array before using it for tracking.
* Can be used to add custom dimensions and metrics on your own or to later existing product attributes based on your own logic.
*
* Called before outputting any of the following ecommerce action.
* The action can be identified using the attributes_used_for parameter of the filter.
*
* purchase: order received page
* cart: cart page
* checkout: checkout page
* productdetail: product detail page
* readdedtocart: user clicked on the “Undo” link on the cart page after removing an item
* addtocartsingle: product added to cart
* widgetproduct: product shown in a sidebar widget
* productlist: product shown in a product list (category page or special product list like ‘New products’)
* groupedproductlist: product shown on a product detail page of a grouped product
*
* @param array $_temp_productdata An associative array containing all GA4 product attributes as well as any custom attribute
* @param string $attributes_used_for The name of the ecommerce action where this product will be used
*/
return apply_filters( GTM4WP_WPFILTER_EEC_PRODUCT_ARRAY, $_temp_productdata, $attributes_used_for );
}
/**
* Takes a WooCommerce order and returns an associative array that can be used
* for enhanced ecommerce tracking and Google Ads dynamic remarketing (legacy version).
*
* @param WC_Order $order The order that needs to be processed.
* @return array An array with an array of product data.
*/
function gtm4wp_woocommerce_process_order_items( $order ) {
$order_data = array();
if ( ! $order ) {
return $order_data;
}
if ( ! ( $order instanceof WC_Order ) ) {
return $order_data;
}
$order_items = $order->get_items();
if ( $order_items ) {
foreach ( $order_items as $order_item ) {
/**
* This filter allows 3rd party code to exclude specific products from reporting.
*
* @param bool true Constant value telling 3rd party code that the order item will be included in reporting if not changed by the filter.
* @param WC_Order_Item $order_item The order item object retrived from WooCommerce.
*
* return bool If the filter returns false, the order item will be omitted from processing.
*/
if ( ! apply_filters( GTM4WP_WPFILTER_EEC_ORDER_ITEM, true, $order_item ) ) {
continue;
}
$product = $order_item->get_product();
$inc_tax = ( 'incl' === get_option( 'woocommerce_tax_display_shop' ) );
$product_price = round( (float) $order->get_item_total( $order_item, $inc_tax ), 2 );
$eec_product_array = gtm4wp_woocommerce_process_product(
$product,
array(
'quantity' => $order_item->get_quantity(),
'price' => $product_price,
),
'purchase'
);
unset( $eec_product_array['internal_id'] );
if ( $eec_product_array ) {
$order_data[] = $eec_product_array;
}
}
}
// No need to apply a filter here since all products in the array have been already filtered in gtm4wp_woocommerce_process_product().
return $order_data;
}
/**
* Returns an associative array that can be used in the data layer to output the raw order data.
*
* @param WC_Order $order The WooCommerce order object.
* @param array $order_items An array including product data generated with gtm4wp_woocommerce_process_product().
* @return array
*/
function gtm4wp_woocommerce_get_raw_order_datalayer( $order, $order_items ) {
$order_data = array();
if ( ! ( $order instanceof WC_Order ) ) {
return $order_data;
}
if ( ! is_array( $order_items ) ) {
return $order_data;
}
$billing_email_hash = gtm4wp_normalize_and_hash_email_address( 'sha256', $order->get_billing_email() );
$billing_first_hash = gtm4wp_normalize_and_hash( 'sha256', $order->get_billing_first_name(), false );
$billing_last_hash = gtm4wp_normalize_and_hash( 'sha256', $order->get_billing_last_name(), false );
$billing_phone_hash = gtm4wp_normalize_and_hash( 'sha256', $order->get_billing_phone(), true );
$order_data = array(
'attributes' => array(
'date' => $order->get_date_created()->date( 'c' ),
'order_number' => $order->get_order_number(),
'order_key' => $order->get_order_key(),
'payment_method' => esc_js( $order->get_payment_method() ),
'payment_method_title' => esc_js( $order->get_payment_method_title() ),
'shipping_method' => esc_js( $order->get_shipping_method() ),
'status' => esc_js( $order->get_status() ),
'coupons' => implode( ', ', $order->get_coupon_codes() ),
),
'totals' => array(
'currency' => esc_js( $order->get_currency() ),
'discount_total' => esc_js( $order->get_discount_total() ),
'discount_tax' => esc_js( $order->get_discount_tax() ),
'shipping_total' => esc_js( $order->get_shipping_total() ),
'shipping_tax' => esc_js( $order->get_shipping_tax() ),
'cart_tax' => esc_js( $order->get_cart_tax() ),
'total' => esc_js( $order->get_total() ),
'total_tax' => esc_js( $order->get_total_tax() ),
'total_discount' => esc_js( $order->get_total_discount() ),
'subtotal' => esc_js( $order->get_subtotal() ),
'tax_totals' => $order->get_tax_totals(),
),
'customer' => array(
'id' => $order->get_customer_id(),
'billing' => array(
'first_name' => esc_js( $order->get_billing_first_name() ),
'first_name_hash' => esc_js( $billing_first_hash ),
'last_name' => esc_js( $order->get_billing_last_name() ),
'last_name_hash' => esc_js( $billing_last_hash ),
'company' => esc_js( $order->get_billing_company() ),
'address_1' => esc_js( $order->get_billing_address_1() ),
'address_2' => esc_js( $order->get_billing_address_2() ),
'city' => esc_js( $order->get_billing_city() ),
'state' => esc_js( $order->get_billing_state() ),
'postcode' => esc_js( $order->get_billing_postcode() ),
'country' => esc_js( $order->get_billing_country() ),
'email' => esc_js( $order->get_billing_email() ),
'emailhash' => esc_js( $billing_email_hash ), // deprecated.
'email_hash' => esc_js( $billing_email_hash ),
'phone' => esc_js( $order->get_billing_phone() ),
'phone_hash' => esc_js( $billing_phone_hash ),
),
'shipping' => array(
'first_name' => esc_js( $order->get_shipping_first_name() ),
'last_name' => esc_js( $order->get_shipping_last_name() ),
'company' => esc_js( $order->get_shipping_company() ),
'address_1' => esc_js( $order->get_shipping_address_1() ),
'address_2' => esc_js( $order->get_shipping_address_2() ),
'city' => esc_js( $order->get_shipping_city() ),
'state' => esc_js( $order->get_shipping_state() ),
'postcode' => esc_js( $order->get_shipping_postcode() ),
'country' => esc_js( $order->get_shipping_country() ),
),
),
'items' => $order_items,
);
/**
* Filters the orderData array before using it for tracking.
* Can be used to add custom order or even product data into the data layer.
*
* @param array $order_data An associative array containing all data (head data and products) about the currently placed order.
* @param WC_Order $order The WooCommerce order object.
*/
return apply_filters( GTM4WP_WPFILTER_EEC_ORDER_DATA, $order_data, $order );
}
/**
* Takes a WooCommerce order and order items and generates the standard/classic and
* enhanced ecommerce version of the purchase data layer codes for Universal Analytics.
*
* @param WC_Order $order The WooCommerce order that needs to be transformed into an enhanced ecommerce data layer.
* @param array $order_items The array returned by gtm4wp_woocommerce_process_order_items(). It not set, then function will call gtm4wp_woocommerce_process_order_items().
* @return array The data layer content as an associative array that can be passed to json_encode() to product a JavaScript object used by GTM.
*/
function gtm4wp_woocommerce_get_purchase_datalayer( $order, $order_items = null ) {
global $gtm4wp_options;
$data_layer = array();
if ( $order instanceof WC_Order ) {
if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEXCLUDETAX ] ) {
$order_revenue = (float) ( $order->get_total() - $order->get_total_tax() );
} else {
$order_revenue = (float) $order->get_total();
}
$order_shipping_cost = (float) $order->get_shipping_total();
if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEXCLUDESHIPPING ] ) {
$order_revenue -= $order_shipping_cost;
}
$order_currency = $order->get_currency();
$data_layer['event'] = 'purchase';
$data_layer['ecommerce'] = array(
'currency' => $order_currency,
'transaction_id' => $order->get_order_number(),
'affiliation' => '',
'value' => $order_revenue,
'tax' => (float) $order->get_total_tax(),
'shipping' => (float) ( $order->get_shipping_total() ),
'coupon' => implode( ', ', $order->get_coupon_codes() ),
);
if ( isset( $order_items ) ) {
$_order_items = $order_items;
} else {
$_order_items = gtm4wp_woocommerce_process_order_items( $order );
}
if ( true === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKECOMMERCE ] ) {
$data_layer['ecommerce']['items'] = $_order_items;
}
}
/**
* Filters the ecommerce purchase data layer content.
* Can be used to add custom data to the data layer when the purhcase ecommerce action is included.
*
* @param array $data_layer An associative array containing the full data layer including purchase header attributes.
* @param WC_Order $order The WooCommerce order that needs to be transformed into an enhanced ecommerce data layer.
*/
return apply_filters( GTM4WP_WPFILTER_ECC_PURCHASE_DATALAYER, $data_layer, $order );
}
/**
* Function executed when the main GTM4WP data layer generation happens.
* Hooks into gtm4wp_compile_datalayer.
*
* @param array $data_layer An array of key-value pairs that will be converted into a JavaScript object on the frontend for GTM.
* @return array Extended data layer content with WooCommerce data added.
*/
function gtm4wp_woocommerce_datalayer_filter_items( $data_layer ) {
global $gtm4wp_options, $wp, $gtm4wp_woocommerce_purchase_data_pushed;
if ( array_key_exists( 'HTTP_X_REQUESTED_WITH', $_SERVER ) ) {
return $data_layer;
}
$woo = WC();
// Customer data will be present on every pageview if feature is enabled.
if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCCUSTOMERDATA ] ) {
if ( $woo->customer instanceof WC_Customer ) {
// we need to use this instead of $woo->customer as this will load proper total order number and value from the database instead of the session.
$woo_customer = new WC_Customer( $woo->customer->get_id() );
$data_layer['customerTotalOrders'] = $woo_customer->get_order_count();
$data_layer['customerTotalOrderValue'] = $woo_customer->get_total_spent();
$data_layer['customerFirstName'] = $woo_customer->get_first_name();
$data_layer['customerLastName'] = $woo_customer->get_last_name();
$data_layer['customerBillingFirstName'] = $woo_customer->get_billing_first_name();
$data_layer['customerBillingLastName'] = $woo_customer->get_billing_last_name();
$data_layer['customerBillingCompany'] = $woo_customer->get_billing_company();
$data_layer['customerBillingAddress1'] = $woo_customer->get_billing_address_1();
$data_layer['customerBillingAddress2'] = $woo_customer->get_billing_address_2();
$data_layer['customerBillingCity'] = $woo_customer->get_billing_city();
$data_layer['customerBillingState'] = $woo_customer->get_billing_state();
$data_layer['customerBillingPostcode'] = $woo_customer->get_billing_postcode();
$data_layer['customerBillingCountry'] = $woo_customer->get_billing_country();
$data_layer['customerBillingEmail'] = $woo_customer->get_billing_email();
$data_layer['customerBillingEmailHash'] = gtm4wp_normalize_and_hash_email_address( 'sha256', $woo_customer->get_billing_email() );
$data_layer['customerBillingPhone'] = $woo_customer->get_billing_phone();
$data_layer['customerShippingFirstName'] = $woo_customer->get_shipping_first_name();
$data_layer['customerShippingLastName'] = $woo_customer->get_shipping_last_name();
$data_layer['customerShippingCompany'] = $woo_customer->get_shipping_company();
$data_layer['customerShippingAddress1'] = $woo_customer->get_shipping_address_1();
$data_layer['customerShippingAddress2'] = $woo_customer->get_shipping_address_2();
$data_layer['customerShippingCity'] = $woo_customer->get_shipping_city();
$data_layer['customerShippingState'] = $woo_customer->get_shipping_state();
$data_layer['customerShippingPostcode'] = $woo_customer->get_shipping_postcode();
$data_layer['customerShippingCountry'] = $woo_customer->get_shipping_country();
}
}
// Cart content will be present on every pageview if feature is enabled.
if (
$gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEINCLUDECARTINDL ] &&
isset( $woo ) &&
isset( $woo->cart )
) {
$current_cart = $woo->cart;
$data_layer['cartContent'] = array(
'totals' => array(
'applied_coupons' => $current_cart->get_applied_coupons(),
'discount_total' => $current_cart->get_discount_total(),
'subtotal' => $current_cart->get_subtotal(),
'total' => $current_cart->get_cart_contents_total(),
),
'items' => array(),
);
foreach ( $current_cart->get_cart() as $cart_item_id => $cart_item_data ) {
/**
* Applying WooCommerce's own woocommerce_cart_item_product filter here is essential in order to hide everything
* from tracking codes that is not visible to the user as well.
*/
$product = apply_filters( 'woocommerce_cart_item_product', $cart_item_data['data'], $cart_item_data, $cart_item_id );
/**
* This filter allows 3rd party code to exclude specific products from reporting.
*
* @param bool true Constant value telling 3rd party code that the order item will be included in reporting if not changed by the filter.
* @param array $cart_item_data Associative array generated by WooCommerce returned by the WC()->cart->get_cart() function call.
*
* return bool If the filter returns false, the cart item will be omitted from processing.
*/
if (
! apply_filters( GTM4WP_WPFILTER_EEC_CART_ITEM, true, $cart_item_data )
|| ! apply_filters( 'woocommerce_widget_cart_item_visible', true, $cart_item_data, $cart_item_id )
) {
continue;
}
$eec_product_array = gtm4wp_woocommerce_process_product(
$product,
array(
'quantity' => $cart_item_data['quantity'],
),
'cart'
);
unset( $eec_product_array['internal_id'] );
$data_layer['cartContent']['items'][] = $eec_product_array;
}
}
// Product detail view data layer content.
if ( is_product() ) {
if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKECOMMERCE ] ) {
$postid = get_the_ID();
$product = wc_get_product( $postid );
$eec_product_array = gtm4wp_woocommerce_process_product(
$product,
array(),
'productdetail'
);
$data_layer['productRatingCounts'] = $product->get_rating_counts();
$data_layer['productAverageRating'] = (float) $product->get_average_rating();
$data_layer['productReviewCount'] = (int) $product->get_review_count();
$data_layer['productType'] = $product->get_type();
switch ( $data_layer['productType'] ) {
case 'variable':
$data_layer['productIsVariable'] = 1;
if ( true === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCVIEWITEMONPARENT ] ) {
$gtm4wp_currency = get_woocommerce_currency();
unset( $eec_product_array['internal_id'] );
gtm4wp_datalayer_push(
'view_item',
array(
'ecommerce' => array(
'currency' => $gtm4wp_currency,
'value' => $eec_product_array['price'],
'items' => array(
$eec_product_array,
),
),
)
);
}
break;
case 'grouped':
$data_layer['productIsVariable'] = 0;
break;
default:
$data_layer['productIsVariable'] = 0;
$gtm4wp_currency = get_woocommerce_currency();
unset( $eec_product_array['internal_id'] );
gtm4wp_datalayer_push(
'view_item',
array(
'ecommerce' => array(
'currency' => $gtm4wp_currency,
'value' => $eec_product_array['price'],
'items' => array(
$eec_product_array,
),
),
)
);
}
}
} elseif ( is_cart() ) {
// Cart page data layer content.
if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKECOMMERCE ] ) {
$gtm4wp_cart_products = array();
$gtm4wp_cart_total = 0;
$gtm4wp_currency = get_woocommerce_currency();
foreach ( $woo->cart->get_cart() as $cart_item_id => $cart_item_data ) {
/**
* Applying WooCommerce's own woocommerce_cart_item_product filter here is essential in order to hide everything
* from tracking codes that is not visible to the user as well.
*/
$product = apply_filters( 'woocommerce_cart_item_product', $cart_item_data['data'], $cart_item_data, $cart_item_id );
/**
* This filter allows 3rd party code to exclude specific products from reporting.
*
* @param bool true Constant value telling 3rd party code that the order item will be included in reporting if not changed by the filter.
* @param array $cart_item_data Associative array generated by WooCommerce returned by the WC()->cart->get_cart() function call.
*
* return bool If the filter returns false, the cart item will be omitted from processing.
*/
if ( ! apply_filters( GTM4WP_WPFILTER_EEC_CART_ITEM, true, $cart_item_data ) ) {
continue;
}
$eec_product_array = gtm4wp_woocommerce_process_product(
$product,
array(
'quantity' => $cart_item_data['quantity'],
),
'cart'
);
unset( $eec_product_array['internal_id'] );
$gtm4wp_cart_products[] = $eec_product_array;
$gtm4wp_cart_total += $eec_product_array['price'] * $eec_product_array['quantity'];
}
// Do not fire GTM event if no products are in the cart.
if ( count( $gtm4wp_cart_products ) > 0 ) {
gtm4wp_datalayer_push(
'view_cart',
array(
'ecommerce' => array(
'currency' => $gtm4wp_currency,
'value' => $gtm4wp_cart_total,
'items' => $gtm4wp_cart_products,
),
)
);
}
}
} elseif ( is_order_received_page() ) {
// Order received page data layer content.
$do_not_flag_tracked_order = (bool) ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCNOORDERTRACKEDFLAG ] );
// Supressing 'Processing form data without nonce verification.' message as there is no nonce accesible in this case.
$order_id = filter_var( wp_unslash( isset( $_GET['order'] ) ? $_GET['order'] : '' ), FILTER_VALIDATE_INT ); // phpcs:ignore
if ( ! $order_id && isset( $wp->query_vars['order-received'] ) ) {
$order_id = $wp->query_vars['order-received'];
}
$order_id = absint( $order_id );
$order_id_filtered = apply_filters( 'woocommerce_thankyou_order_id', $order_id );
if ( '' !== $order_id_filtered ) {
$order_id = $order_id_filtered;
}
// Supressing 'Processing form data without nonce verification.' message as there is no nonce accesible in this case.
$order_key = isset( $_GET['key'] ) ? wc_clean( sanitize_text_field( wp_unslash( $_GET['key'] ) ) ) : ''; // phpcs:ignore
$order_key = apply_filters( 'woocommerce_thankyou_order_key', $order_key );
if ( $order_id > 0 ) {
$order = wc_get_order( $order_id );
if ( $order instanceof WC_Order ) {
$this_order_key = $order->get_order_key();
if ( $this_order_key !== $order_key ) {
unset( $order );
}
} else {
unset( $order );
}
}
/**
* From this point if for any reason purchase data is not pushed
* that is because for a specific reason.
* In any other case woocommerce_thankyou hook will be the fallback if
* is_order_received_page does not work.
*/
$gtm4wp_woocommerce_purchase_data_pushed = true;
if ( isset( $order ) && $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCORDERMAXAGE ] ) {
if ( $order->is_paid() && $order->get_date_paid() ) {
$now = new DateTime( 'now', $order->get_date_paid()->getTimezone() );
$diff = $now->diff( $order->get_date_paid() );
$minutes = ( $diff->days * 24 * 60 ) + ( $diff->h * 60 ) + $diff->i;
} else {
$now = new DateTime( 'now', $order->get_date_created()->getTimezone() );
$diff = $now->diff( $order->get_date_created() );
$minutes = ( $diff->days * 24 * 60 ) + ( $diff->h * 60 ) + $diff->i;
}
if ( $minutes > $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCORDERMAXAGE ] ) {
unset( $order );
}
}
$order_items = null;
// Raw order data will be outputted regardless of whether the purhcase has been already tracked previously, since this data is not meant to track using GA.
if ( isset( $order ) && $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCORDERDATA ] ) {
$order_items = gtm4wp_woocommerce_process_order_items( $order );
$data_layer['orderData'] = gtm4wp_woocommerce_get_raw_order_datalayer( $order, $order_items );
}
if ( isset( $order ) && ( 1 === (int) $order->get_meta( '_ga_tracked', true ) ) && ! $do_not_flag_tracked_order ) {
unset( $order );
}
if ( isset( $_COOKIE['gtm4wp_orderid_tracked'] ) ) {
$tracked_order_id = filter_var( wp_unslash( $_COOKIE['gtm4wp_orderid_tracked'] ), FILTER_VALIDATE_INT );
if ( $tracked_order_id && ( $tracked_order_id === $order_id ) && ! $do_not_flag_tracked_order ) {
unset( $order );
}
}
if ( isset( $order ) && ( 'failed' === $order->get_status() ) ) {
// do not track order where payment failed.
unset( $order );
}
if ( isset( $order ) ) {
/**
* Variable for Google Smart Shopping campaign new customer reporting.
*
* @see https://support.google.com/google-ads/answer/9917012?hl=en-AU#zippy=%2Cinstall-with-google-tag-manager
*/
$data_layer['new_customer'] = \Automattic\WooCommerce\Admin\API\Reports\Orders\Stats\DataStore::is_returning_customer( $order ) === false;
$purchase_data_layer = gtm4wp_woocommerce_get_purchase_datalayer( $order, $order_items );
$before_purchase_dl_push = '
// Check whether this order has been already tracked in this browser.
// Read order id already tracked from cookies or local storage.
let gtm4wp_orderid_tracked = "";
if ( !window.localStorage ) {
let gtm4wp_cookie = "; " + document.cookie;
let gtm4wp_cookie_parts = gtm4wp_cookie.split( "; gtm4wp_orderid_tracked=" );
if ( gtm4wp_cookie_parts.length == 2 ) {
gtm4wp_orderid_tracked = gtm4wp_cookie_parts.pop().split(";").shift();
}
} else {
gtm4wp_orderid_tracked = window.localStorage.getItem( "gtm4wp_orderid_tracked" );
}
// Check whether this order has been already tracked before in this browser.
let gtm4wp_order_already_tracked = false;
if ( gtm4wp_orderid_tracked && ( "' . esc_js( $order->get_order_number() ) . '" == gtm4wp_orderid_tracked ) ) {
gtm4wp_order_already_tracked = true;
}
// only push purchase action if not tracked already.
if ( !gtm4wp_order_already_tracked ) {';
$after_purchase_dl_push = '
}
// Store order ID to prevent tracking this purchase again.
if ( !window.localStorage ) {
var gtm4wp_orderid_cookie_expire = new Date();
gtm4wp_orderid_cookie_expire.setTime( gtm4wp_orderid_cookie_expire.getTime() + (365*24*60*60*1000) );
var gtm4wp_orderid_cookie_expires_part = "expires=" + gtm4wp_orderid_cookie_expire.toUTCString();
document.cookie = "gtm4wp_orderid_tracked=" + "' . esc_js( $order->get_order_number() ) . '" + ";" + gtm4wp_orderid_cookie_expires_part + ";path=/";
} else {
window.localStorage.setItem( "gtm4wp_orderid_tracked", "' . esc_js( $order->get_order_number() ) . '" );
}';
gtm4wp_datalayer_push(
$purchase_data_layer['event'],
$purchase_data_layer,
$before_purchase_dl_push,
$after_purchase_dl_push
);
if ( ! $do_not_flag_tracked_order ) {
$order->update_meta_data( '_ga_tracked', 1 );
$order->save();
}
}
} elseif ( is_checkout() ) {
if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKECOMMERCE ] ) {
$gtm4wp_checkout_products = array();
$gtm4wp_checkout_total = 0;
$gtm4wp_currency = get_woocommerce_currency();
foreach ( $woo->cart->get_cart() as $cart_item_id => $cart_item_data ) {
/**
* Applying WooCommerce's own woocommerce_cart_item_product filter here is essential in order to hide everything
* from tracking codes that is not visible to the user as well.
*/
$product = apply_filters( 'woocommerce_cart_item_product', $cart_item_data['data'], $cart_item_data, $cart_item_id );
/**
* This filter allows 3rd party code to exclude specific products from reporting.
*
* @param bool true Constant value telling 3rd party code that the order item will be included in reporting if not changed by the filter.
* @param array $cart_item_data Associative array generated by WooCommerce returned by the WC()->cart->get_cart() function call.
*
* return bool If the filter returns false, the cart item will be omitted from processing.
*/
if ( ! apply_filters( GTM4WP_WPFILTER_EEC_CART_ITEM, true, $cart_item_data ) ) {
continue;
}
$eec_product_array = gtm4wp_woocommerce_process_product(
$product,
array(
'quantity' => $cart_item_data['quantity'],
),
'checkout'
);
unset( $eec_product_array['internal_id'] );
$gtm4wp_checkout_products[] = $eec_product_array;
$gtm4wp_checkout_total += $eec_product_array['quantity'] * $eec_product_array['price'];
} // end foreach cart item
// Do not fire GTM event if no products are in the cart.
if ( count( $gtm4wp_checkout_products ) > 0 ) {
gtm4wp_datalayer_push(
'begin_checkout',
array(
'ecommerce' => array(
'currency' => $gtm4wp_currency,
'value' => $gtm4wp_checkout_total,
'items' => $gtm4wp_checkout_products,
),
)
);
}
wc_enqueue_js(
'
window.gtm4wp_checkout_products = ' . wp_json_encode( $gtm4wp_checkout_products ) . ';
window.gtm4wp_checkout_value = ' . (float) $gtm4wp_checkout_total . ';'
);
}
}
// Handle add_to_cart event when product was readded after removing from the cart.
if ( $woo && $woo->session ) {
$cart_readded_hash = $woo->session->get( 'gtm4wp_product_readded_to_cart' );
if ( isset( $cart_readded_hash ) ) {
$cart_item = $woo->cart->get_cart_item( $cart_readded_hash );
if ( ! empty( $cart_item ) ) {
$product = $cart_item['data'];
$eec_product_array = gtm4wp_woocommerce_process_product(
$product,
array(
'quantity' => $cart_item['quantity'],
),
'readdedtocart'
);
$gtm4wp_currency = get_woocommerce_currency();
unset( $eec_product_array['internal_id'] );
gtm4wp_datalayer_push(
'add_to_cart',
array(
'ecommerce' => array(
'currency' => $gtm4wp_currency,
'value' => $eec_product_array['price'] * $eec_product_array['quantity'],
'items' => array( $eec_product_array ),
),
)
);
}
$woo->session->set( 'gtm4wp_product_readded_to_cart', null );
}
}
gtm4wp_fire_additional_datalayer_pushes();
return apply_filters( GTM4WP_WPFILTER_EEC_DATALAYER_PAGELOAD, $data_layer );
}
/**
* Executed during woocommerce_thankyou.
* This is a fallback function to output purchase data layer on customized order received pages where
* the is_order_received_page() template tag returns false for some reason.
*
* @param int $order_id The ID of the order placed by the user just recently.
* @return void
*/
function gtm4wp_woocommerce_thankyou( $order_id ) {
global $gtm4wp_options, $gtm4wp_woocommerce_purchase_data_pushed, $gtm4wp_datalayer_name;
if ( function_exists('is_order_received_page') && is_order_received_page() ) {
return;
}
/*
If this flag is set to true, it means that the puchase event was fired
when capturing the is_order_received_page template tag therefore
no need to handle this here twice
*/
if ( $gtm4wp_woocommerce_purchase_data_pushed ) {
return;
}
if ( $order_id > 0 ) {
$order = wc_get_order( $order_id );
}
$data_layer = array();
if ( isset( $order ) && $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCORDERMAXAGE ] ) {
$now = new DateTime( 'now', $order->get_date_created()->getTimezone() );
if ( $order->is_paid() && $order->get_date_paid() ) {
$diff = $now->diff( $order->get_date_paid() );
$minutes = ( $diff->days * 24 * 60 ) + ( $diff->h * 60 ) + $diff->i;
} else {
$diff = $now->diff( $order->get_date_created() );
$minutes = ( $diff->days * 24 * 60 ) + ( $diff->h * 60 ) + $diff->i;
}
if ( $minutes > $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCORDERMAXAGE ] ) {
unset( $order );
}
}
$order_items = null;
// Raw order data will be outputted regardless of whether the purhcase has been already tracked previously, since this data is not meant to track using GA.
if ( isset( $order ) && $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCORDERDATA ] ) {
$order_items = gtm4wp_woocommerce_process_order_items( $order );
$data_layer['orderData'] = gtm4wp_woocommerce_get_raw_order_datalayer( $order, $order_items );
}
$do_not_flag_tracked_order = (bool) ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCNOORDERTRACKEDFLAG ] );
if ( isset( $order ) && ( 1 === (int) $order->get_meta( '_ga_tracked', true ) ) && ! $do_not_flag_tracked_order ) {
unset( $order );
}
if ( isset( $_COOKIE['gtm4wp_orderid_tracked'] ) ) {
$tracked_order_id = filter_var( wp_unslash( $_COOKIE['gtm4wp_orderid_tracked'] ), FILTER_VALIDATE_INT );
if ( $tracked_order_id && ( $tracked_order_id === $order_id ) && ! $do_not_flag_tracked_order ) {
unset( $order );
}
}
if ( isset( $order ) && ( 'failed' === $order->get_status() ) ) {
// do not track order where payment failed.
unset( $order );
}
if ( isset( $order ) ) {
/**
* Variable for Google Smart Shopping campaign new customer reporting.
*
* @see https://support.google.com/google-ads/answer/9917012?hl=en-AU#zippy=%2Cinstall-with-google-tag-manager
*/
$data_layer['new_customer'] = \Automattic\WooCommerce\Admin\API\Reports\Orders\Stats\DataStore::is_returning_customer( $order ) === false;
$purchase_data_layer = gtm4wp_woocommerce_get_purchase_datalayer( $order, $order_items );
$data_layer = array_merge(
$data_layer,
$purchase_data_layer
);
$script_tag = '
' . gtm4wp_generate_script_opening_tag() . '
window.' . esc_js( $gtm4wp_datalayer_name ) . ' = window.' . esc_js( $gtm4wp_datalayer_name ) . ' || [];
window.' . esc_js( $gtm4wp_datalayer_name ) . '.push(' . wp_json_encode( $data_layer ) . ');
</script>';
echo htmlspecialchars_decode( //phpcs:ignore
wp_kses(
$script_tag,
gtm4wp_get_sanitize_script_block_rules()
)
);
if ( ! $do_not_flag_tracked_order ) {
$order->update_meta_data( '_ga_tracked', 1 );
$order->save();
}
}
}
/**
* Function executed with the woocommerce_after_add_to_cart_button hook.
*
* @return void
*/
function gtm4wp_woocommerce_single_add_to_cart_tracking() {
global $product, $gtm4wp_options;
// exit early if there is nothing to do.
if ( false === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKECOMMERCE ]
|| ! empty( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCBLOCKSADDTOCART ] ) ) {
return;
}
$eec_product_array = gtm4wp_woocommerce_process_product(
$product,
array(),
'addtocartsingle'
);
echo '<input type="hidden" name="gtm4wp_product_data" value="' . esc_attr( wp_json_encode( $eec_product_array ) ) . '" />' . "\n";
}
/**
* Ecommerce product array with the product that is currently shown in the cart.
*