DuracellTomi's Google Tag Manager for WordPress - Version 1.14

Version Description

  • Added: support for tracking WooCommerce Block based product lists, except the "All Products" block
  • Added: support for new_customer parameter for Google Smart Shopping campaigns
  • Added: SHA256 hashed versions of data layer variables containing email addresses: customerBillingEmailHash on WooCommerce order received pages and visitorEmailHash on generic uses cases
  • Added: WooCommerce - if for some reason is_order_received_page() reports false on the order received page, woocommerce_thankyou hook will be used as backup
  • Updated: removed jQuery dependency from plugin modules: contact form 7 integration, form move tracker, Vimeo, YouTube, Soundcloud, partly WooCommerce
  • Updated: moved the hidden helper span element in products lists to the end of the product box to make more compatible with themes
  • Updated: more consistent retrieval of product categories - by Dekadinious
  • Updated: gtm4wp_product_readded_to_cart cookie replaced with a WooCommerce session variable to use fewer cookies in this plugin
  • Updated: gtm4wp_user_logged_in, gtm4wp_user_registered and gtm4wp_last_weatherstatus cookies are now HTTP only cookies
  • Updated: replaced deprecated jQuery method and event usage in WP admin
  • Updated: added rel="noopener" to links pointing to external sites on WP admin page
  • Updated: Hiding the iframe tag from assistive technologies as it provides no functionality for the end user. This will also alleviate a11y audit warnings.
  • Fixed: proper values for visitorType data layer variable
  • Fixed: replaced unsafe usage of eval() in WooCommerce QuickView plugin integration
  • Fixed: type check of the order ID obtained from a cookie before using the value
  • Fixed: navigation issues in Safari if browser loads previous page from cache. GTM4WP will now force Safari to always reload pages.
  • Fixed: Do not trigger browser change event in WooCommerce checkout page submit event handler. It caused issues with other 3rd party plugins.
  • Fixed: HTML5 detection. - by Sjoerd
  • Fixed: Username not included in datalayer if no other user attribute is included - by StaymanHou
Download this release

Release Info

Developer duracelltomi
Plugin Icon 128x128 DuracellTomi's Google Tag Manager for WordPress
Version 1.14
Comparing to
See all releases

Code changes from version 1.13.1 to 1.14

admin/admin.php CHANGED
@@ -1,1484 +1,1500 @@
1
- <?php
2
- define( 'GTM4WP_ADMINSLUG', 'gtm4wp-settings' );
3
- define( 'GTM4WP_ADMIN_GROUP', 'gtm4wp-admin-group' );
4
-
5
- define( 'GTM4WP_ADMIN_GROUP_GENERAL', 'gtm4wp-admin-group-general' );
6
- define( 'GTM4WP_ADMIN_GROUP_GTMID', 'gtm4wp-admin-group-gtm-id' );
7
- define( 'GTM4WP_ADMIN_GROUP_PLACEMENT', 'gtm4wp-admin-code-placement' );
8
- define( 'GTM4WP_ADMIN_GROUP_INFO', 'gtm4wp-admin-group-datalayer-info' );
9
-
10
- define( 'GTM4WP_ADMIN_GROUP_INCLUDES', 'gtm4wp-admin-group-includes' );
11
- define( 'GTM4WP_ADMIN_GROUP_EVENTS', 'gtm4wp-admin-group-events' );
12
- define( 'GTM4WP_ADMIN_GROUP_SCROLLER', 'gtm4wp-admin-group-scroller' );
13
- define( 'GTM4WP_ADMIN_GROUP_BLACKLIST', 'gtm4wp-admin-group-blacklist-tags' );
14
- define( 'GTM4WP_ADMIN_GROUP_INTEGRATION', 'gtm4wp-admin-group-integration' );
15
- define( 'GTM4WP_ADMIN_GROUP_ADVANCED', 'gtm4wp-admin-group-advanced' );
16
- define( 'GTM4WP_ADMIN_GROUP_CREDITS', 'gtm4wp-admin-group-credits' );
17
-
18
- define( 'GTM4WP_USER_NOTICES_KEY', 'gtm4wp_user_notices_dismisses' );
19
-
20
- define( 'GTM4WP_PHASE_STABLE', 'gtm4wp-phase-stable' );
21
- define( 'GTM4WP_PHASE_BETA', 'gtm4wp-phase-beta' );
22
- define( 'GTM4WP_PHASE_EXPERIMENTAL', 'gtm4wp-phase-experimental' );
23
- define( 'GTM4WP_PHASE_DEPRECATED', 'gtm4wp-phase-deprecated' );
24
-
25
- $GLOBALS['gtm4wp_def_user_notices_dismisses'] = array(
26
- 'enter-gtm-code' => false,
27
- 'wc-ga-plugin-warning' => false,
28
- 'wc-gayoast-plugin-warning' => false,
29
- 'php72-warning' => false,
30
- 'deprecated-warning' => false,
31
- );
32
-
33
- $GLOBALS['gtm4wp_includefieldtexts'] = array(
34
- GTM4WP_OPTION_INCLUDE_POSTTYPE => array(
35
- 'label' => __( 'Posttype of current post/archive', 'duracelltomi-google-tag-manager' ),
36
- 'description' => __( 'Check this option to include the type of the current post or archive page (post, page or any custom post type).', 'duracelltomi-google-tag-manager' ),
37
- 'phase' => GTM4WP_PHASE_STABLE,
38
- ),
39
- GTM4WP_OPTION_INCLUDE_CATEGORIES => array(
40
- 'label' => __( 'Category list of current post/archive', 'duracelltomi-google-tag-manager' ),
41
- 'description' => __( 'Check this option to include the category names of the current post or archive page', 'duracelltomi-google-tag-manager' ),
42
- 'phase' => GTM4WP_PHASE_STABLE,
43
- ),
44
- GTM4WP_OPTION_INCLUDE_TAGS => array(
45
- 'label' => __( 'Tags of current post', 'duracelltomi-google-tag-manager' ),
46
- 'description' => __( 'Check this option to include the tags of the current post.', 'duracelltomi-google-tag-manager' ),
47
- 'phase' => GTM4WP_PHASE_STABLE,
48
- ),
49
- GTM4WP_OPTION_INCLUDE_AUTHORID => array(
50
- 'label' => __( 'Post author ID', 'duracelltomi-google-tag-manager' ),
51
- 'description' => __( 'Check this option to include the ID of the author on the current post or author page.', 'duracelltomi-google-tag-manager' ),
52
- 'phase' => GTM4WP_PHASE_STABLE,
53
- ),
54
- GTM4WP_OPTION_INCLUDE_AUTHOR => array(
55
- 'label' => __( 'Post author name', 'duracelltomi-google-tag-manager' ),
56
- 'description' => __( 'Check this option to include the name of the author on the current post or author page.', 'duracelltomi-google-tag-manager' ),
57
- 'phase' => GTM4WP_PHASE_STABLE,
58
- ),
59
- GTM4WP_OPTION_INCLUDE_POSTDATE => array(
60
- 'label' => __( 'Post date', 'duracelltomi-google-tag-manager' ),
61
- 'description' => __( 'Check this option to include the date of the current post. This will include 4 dataLayer variables: full date, post year, post month, post date.', 'duracelltomi-google-tag-manager' ),
62
- 'phase' => GTM4WP_PHASE_STABLE,
63
- ),
64
- GTM4WP_OPTION_INCLUDE_POSTTITLE => array(
65
- 'label' => __( 'Post title', 'duracelltomi-google-tag-manager' ),
66
- 'description' => __( 'Check this option to include the title of the current post.', 'duracelltomi-google-tag-manager' ),
67
- 'phase' => GTM4WP_PHASE_STABLE,
68
- ),
69
- GTM4WP_OPTION_INCLUDE_POSTCOUNT => array(
70
- 'label' => __( 'Post count', 'duracelltomi-google-tag-manager' ),
71
- 'description' => __( 'Check this option to include the count of the posts currently shown on the page and the total number of posts in the category/tag/any taxonomy.', 'duracelltomi-google-tag-manager' ),
72
- 'phase' => GTM4WP_PHASE_STABLE,
73
- ),
74
- GTM4WP_OPTION_INCLUDE_POSTID => array(
75
- 'label' => __( 'Post ID', 'duracelltomi-google-tag-manager' ),
76
- 'description' => __( 'Check this option to include the post id.', 'duracelltomi-google-tag-manager' ),
77
- 'phase' => GTM4WP_PHASE_STABLE,
78
- ),
79
- GTM4WP_OPTION_INCLUDE_POSTFORMAT => array(
80
- 'label' => __( 'Post Format', 'duracelltomi-google-tag-manager' ),
81
- 'description' => __( 'Check this option to include the post format.', 'duracelltomi-google-tag-manager' ),
82
- 'phase' => GTM4WP_PHASE_STABLE,
83
- ),
84
- GTM4WP_OPTION_INCLUDE_POSTTERMLIST => array(
85
- "label" => __( "Post Terms", 'duracelltomi-google-tag-manager' ),
86
- "description" => __( "Check this option to include taxonomy values associated with a given post.", 'duracelltomi-google-tag-manager' ),
87
- "phase" => GTM4WP_PHASE_STABLE
88
- ),
89
- GTM4WP_OPTION_INCLUDE_SEARCHDATA => array(
90
- 'label' => __( 'Search data', 'duracelltomi-google-tag-manager' ),
91
- 'description' => __( 'Check this option to include the search term, referring page URL and number of results on the search page.', 'duracelltomi-google-tag-manager' ),
92
- 'phase' => GTM4WP_PHASE_STABLE,
93
- ),
94
- GTM4WP_OPTION_INCLUDE_LOGGEDIN => array(
95
- 'label' => __( 'Logged in status', 'duracelltomi-google-tag-manager' ),
96
- 'description' => __( 'Check this option to include whether there is a logged in user on your website.', 'duracelltomi-google-tag-manager' ),
97
- 'phase' => GTM4WP_PHASE_STABLE,
98
- ),
99
- GTM4WP_OPTION_INCLUDE_USERROLE => array(
100
- 'label' => __( 'Logged in user role', 'duracelltomi-google-tag-manager' ),
101
- 'description' => __( 'Check this option to include the role of the logged in user.', 'duracelltomi-google-tag-manager' ),
102
- 'phase' => GTM4WP_PHASE_STABLE,
103
- ),
104
- GTM4WP_OPTION_INCLUDE_USERID => array(
105
- 'label' => __( 'Logged in user ID', 'duracelltomi-google-tag-manager' ),
106
- 'description' => __( 'Check this option to include the ID of the logged in user.', 'duracelltomi-google-tag-manager' ),
107
- 'phase' => GTM4WP_PHASE_STABLE,
108
- ),
109
- GTM4WP_OPTION_INCLUDE_USERNAME => array(
110
- 'label' => __( 'Logged in user name', 'duracelltomi-google-tag-manager' ),
111
- 'description' => __( 'Check this option to include the username of the logged in user.', 'duracelltomi-google-tag-manager' ),
112
- 'phase' => GTM4WP_PHASE_STABLE,
113
- ),
114
- GTM4WP_OPTION_INCLUDE_USEREMAIL => array(
115
- 'label' => __( 'Logged in user email', 'duracelltomi-google-tag-manager' ),
116
- 'description' => __( 'Check this option to include the email address of the logged in user.', 'duracelltomi-google-tag-manager' ),
117
- 'phase' => GTM4WP_PHASE_STABLE,
118
- ),
119
- GTM4WP_OPTION_INCLUDE_USERREGDATE => array(
120
- 'label' => __( 'Logged in user creation date', 'duracelltomi-google-tag-manager' ),
121
- 'description' => __( 'Check this option to include the date of creation (registration) of the logged in user.', 'duracelltomi-google-tag-manager' ),
122
- 'phase' => GTM4WP_PHASE_STABLE,
123
- ),
124
- GTM4WP_OPTION_INCLUDE_VISITOR_IP => array(
125
- 'label' => __( 'Visitor IP', 'duracelltomi-google-tag-manager' ),
126
- 'description' => __( 'Check this option to include the IP address of the visitor. You might use this to filter internal traffic inside your GTM container. Please be aware that per GDPR its not allowed to transmit this full IP address to Google Analytics or to any other measurement system without explicit consent from the visitor.', 'duracelltomi-google-tag-manager' ),
127
- 'phase' => GTM4WP_PHASE_STABLE,
128
- ),
129
- GTM4WP_OPTION_INCLUDE_REMARKETING => array(
130
- 'label' => __( 'Remarketing variable', 'duracelltomi-google-tag-manager' ),
131
- 'description' => __( 'Check this option to include a dataLayer variable where all dataLayer values are stored to be included in your Google Ads remarketing tag as a custom variable field', 'duracelltomi-google-tag-manager' ),
132
- 'phase' => GTM4WP_PHASE_DEPRECATED,
133
- ),
134
- GTM4WP_OPTION_INCLUDE_BROWSERDATA => array(
135
- 'label' => __( 'Browser data *', 'duracelltomi-google-tag-manager' ),
136
- 'description' => __( 'Check this option to include the name, version and engine data of the browser the visitor uses.', 'duracelltomi-google-tag-manager' )
137
- ),
138
- GTM4WP_OPTION_INCLUDE_OSDATA => array(
139
- 'label' => __( 'OS data *', 'duracelltomi-google-tag-manager' ),
140
- 'description' => __( 'Check this option to include the name and version of the operating system the visitor uses.', 'duracelltomi-google-tag-manager' )
141
- ),
142
- GTM4WP_OPTION_INCLUDE_DEVICEDATA => array(
143
- 'label' => __( 'Device data *', 'duracelltomi-google-tag-manager' ),
144
- 'description' => __( 'Check this option to include the type of device the user is currently using (desktop, tablet or mobile) including manufacturer and model data.', 'duracelltomi-google-tag-manager' )
145
- ),
146
- GTM4WP_OPTION_INCLUDE_MISCGEO => array(
147
- 'label' => __( 'Geo data', 'duracelltomi-google-tag-manager' ),
148
- 'description' => __( 'Add geo data (latitude, longitude, country, city, etc) of the current visitor (provided by ipstack.com)', 'duracelltomi-google-tag-manager' ),
149
- 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
150
- ),
151
- GTM4WP_OPTION_INCLUDE_MISCGEOAPI => array(
152
- 'label' => __( 'IPStack.com API key', 'duracelltomi-google-tag-manager' ),
153
- 'description' => sprintf( __( 'Enter your IPStack.com API key here. <a href="%s" target="_blank">Get a free API key here</a>.', 'duracelltomi-google-tag-manager' ), 'https://ipstack.com/product?utm_source=gtm4wp&utm_medium=link&utm_campaign=gtm4wp-google-tag-manager-for-wordpress' ),
154
- 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
155
- ),
156
- GTM4WP_OPTION_INCLUDE_MISCGEOCF => array(
157
- 'label' => __( 'Cloudflare country code', 'duracelltomi-google-tag-manager' ),
158
- 'description' => __( 'Add the country code of the user provided by Cloudflare (if Cloudflare is used with your site)', 'duracelltomi-google-tag-manager' ),
159
- 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
160
- ),
161
- GTM4WP_OPTION_INCLUDE_WEATHER => array(
162
- 'label' => __( 'Weather data', 'duracelltomi-google-tag-manager' ),
163
- 'description' => sprintf(
164
- __(
165
- 'Check this option to include the current weather conditions around the current visitor.<br /><br />' .
166
- '<strong>Attention!</strong> This feature uses <a href="%s" target="_blank">ipstack.com</a> and ' .
167
- '<a href="%s" target="_blank">openweathermap.org</a> to collect data.<br />' .
168
- "Depending on your website's traffic, additional fees may apply!<br />" .
169
- 'This plugin caches weather data for 1 hour to lower the need to access those services.<br /><br />' .
170
- 'If you activate weather data, <strong>you will need</strong> to add an IPStack.com API key regardless of whether you ' .
171
- "activate the 'Geo data' option!",
172
- 'duracelltomi-google-tag-manager'
173
- ),
174
- 'https://ipstack.com/product?utm_source=gtm4wp&utm_medium=link&utm_campaign=gtm4wp-google-tag-manager-for-wordpress',
175
- 'http://openweathermap.org/price?utm_source=gtm4wp&utm_medium=link&utm_campaign=gtm4wp-google-tag-manager-for-wordpress'
176
- ),
177
- 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
178
- ),
179
- GTM4WP_OPTION_INCLUDE_WEATHERUNITS => array(
180
- 'label' => __( 'Weather data units', 'duracelltomi-google-tag-manager' ),
181
- 'description' => __( 'Select which temperature units you would like to use.', 'duracelltomi-google-tag-manager' ),
182
- 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
183
- ),
184
- GTM4WP_OPTION_INCLUDE_WEATHEROWMAPI => array(
185
- 'label' => __( 'OpenWeatherMap API key', 'duracelltomi-google-tag-manager' ),
186
- 'description' => sprintf( __( 'Enter your OpenWeatherMap API key here. <a href="%s" target="_blank">Get a free API key here</a>.', 'duracelltomi-google-tag-manager' ), 'http://openweathermap.org/price?utm_source=gtm4wp&utm_medium=link&utm_campaign=gtm4wp-google-tag-manager-for-wordpress' ),
187
- 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
188
- ),
189
- GTM4WP_OPTION_INCLUDE_SITEID => array(
190
- 'label' => __( 'Site ID', 'duracelltomi-google-tag-manager' ),
191
- 'description' => __( 'ID of the current site in a WordPress Multisite environment', 'duracelltomi-google-tag-manager' ),
192
- 'phase' => GTM4WP_PHASE_STABLE,
193
- ),
194
- GTM4WP_OPTION_INCLUDE_SITENAME => array(
195
- 'label' => __( 'Site name', 'duracelltomi-google-tag-manager' ),
196
- 'description' => __( 'Name of the current site in a WordPress Multisite environment', 'duracelltomi-google-tag-manager' ),
197
- 'phase' => GTM4WP_PHASE_STABLE,
198
- ),
199
- );
200
-
201
- $GLOBALS['gtm4wp_eventfieldtexts'] = array(
202
- GTM4WP_OPTION_EVENTS_FORMMOVE => array(
203
- 'label' => __( 'Form fill events (gtm4wp.formElementEnter & gtm4wp.formElementLeave)', 'duracelltomi-google-tag-manager' ),
204
- 'description' => __( 'Check this option to include a Tag Manager event when a visitor moves between elements of a form (comment, contact, etc).', 'duracelltomi-google-tag-manager' ),
205
- 'phase' => GTM4WP_PHASE_STABLE,
206
- ),
207
- GTM4WP_OPTION_EVENTS_NEWUSERREG => array(
208
- 'label' => __( 'New user registration', 'duracelltomi-google-tag-manager' ),
209
- 'description' => __( 'Check this option to include a Tag Manager event when a new user registration has been completed on the frontend of your site (admin events not included)', 'duracelltomi-google-tag-manager' ),
210
- 'phase' => GTM4WP_PHASE_STABLE,
211
- ),
212
- GTM4WP_OPTION_EVENTS_USERLOGIN => array(
213
- 'label' => __( 'User logged in', 'duracelltomi-google-tag-manager' ),
214
- 'description' => __( 'Check this option to include a Tag Manager event when an existing user has been logged in on the frontend of your site (admin events not included)', 'duracelltomi-google-tag-manager' ),
215
- 'phase' => GTM4WP_PHASE_STABLE,
216
- ),
217
- GTM4WP_OPTION_EVENTS_YOUTUBE => array(
218
- 'label' => __( 'YouTube video events', 'duracelltomi-google-tag-manager' ),
219
- 'description' => __( 'Check this option to include a Tag Manager event when a visitor interacts with a YouTube video embeded on your site.', 'duracelltomi-google-tag-manager' ),
220
- 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
221
- ),
222
- GTM4WP_OPTION_EVENTS_VIMEO => array(
223
- 'label' => __( 'Vimeo video events', 'duracelltomi-google-tag-manager' ),
224
- 'description' => __( 'Check this option to include a Tag Manager event when a visitor interacts with a Vimeo video embeded on your site.', 'duracelltomi-google-tag-manager' ),
225
- 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
226
- ),
227
- GTM4WP_OPTION_EVENTS_SOUNDCLOUD => array(
228
- 'label' => __( 'Soundcloud events', 'duracelltomi-google-tag-manager' ),
229
- 'description' => __( 'Check this option to include a Tag Manager event when a visitor interacts with a Soundcloud media embeded on your site.', 'duracelltomi-google-tag-manager' ),
230
- 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
231
- )
232
- );
233
-
234
- $GLOBALS['gtm4wp_scrollerfieldtexts'] = array(
235
- GTM4WP_OPTION_SCROLLER_ENABLED => array(
236
- 'label' => __( 'Enabled', 'duracelltomi-google-tag-manager' ),
237
- 'description' => __( 'Enable scroll tracker script on your website.', 'duracelltomi-google-tag-manager' ),
238
- 'phase' => GTM4WP_PHASE_STABLE,
239
- ),
240
- GTM4WP_OPTION_SCROLLER_DEBUGMODE => array(
241
- 'label' => __( 'Debug mode', 'duracelltomi-google-tag-manager' ),
242
- 'description' => __( 'Fire console.log() commands instead of dataLayer events.', 'duracelltomi-google-tag-manager' ),
243
- 'phase' => GTM4WP_PHASE_STABLE,
244
- ),
245
- GTM4WP_OPTION_SCROLLER_CALLBACKTIME => array(
246
- 'label' => __( 'Time delay before location check', 'duracelltomi-google-tag-manager' ),
247
- 'description' => __( 'Enter the number of milliseconds after the script checks the current location. It prevents too many events being fired while scrolling.', 'duracelltomi-google-tag-manager' ),
248
- 'phase' => GTM4WP_PHASE_STABLE,
249
- ),
250
- GTM4WP_OPTION_SCROLLER_DISTANCE => array(
251
- 'label' => __( 'Minimum distance', 'duracelltomi-google-tag-manager' ),
252
- 'description' => __( 'The minimum amount of pixels that a visitor has to scroll before we treat the move as scrolling.', 'duracelltomi-google-tag-manager' ),
253
- 'phase' => GTM4WP_PHASE_STABLE,
254
- ),
255
- GTM4WP_OPTION_SCROLLER_CONTENTID => array(
256
- 'label' => __( 'Content ID', 'duracelltomi-google-tag-manager' ),
257
- 'description' => __( 'Enter the DOM ID of the content element in your template. Leave it empty for default(content). Do not include the # sign.', 'duracelltomi-google-tag-manager' ),
258
- 'phase' => GTM4WP_PHASE_STABLE,
259
- ),
260
- GTM4WP_OPTION_SCROLLER_READERTIME => array(
261
- 'label' => __( 'Scroller time', 'duracelltomi-google-tag-manager' ),
262
- 'description' => __( 'Enter the number of seconds after the the scroller user is being treated as a reader, someone who really reads the content, not just scrolls through it.', 'duracelltomi-google-tag-manager' ),
263
- 'phase' => GTM4WP_PHASE_STABLE,
264
- ),
265
- );
266
-
267
- $GLOBALS['gtm4wp_integratefieldtexts'] = array(
268
- GTM4WP_OPTION_INTEGRATE_WPCF7 => array(
269
- 'label' => __( 'Contact Form 7', 'duracelltomi-google-tag-manager' ),
270
- 'description' => __( 'Check this to include a dataLayer event after a successfull form submission.', 'duracelltomi-google-tag-manager' ),
271
- 'phase' => GTM4WP_PHASE_STABLE,
272
- 'plugintocheck' => 'contact-form-7/wp-contact-form-7.php',
273
- ),
274
- GTM4WP_OPTION_INTEGRATE_WCTRACKCLASSICEC => array(
275
- 'label' => __( 'Track classic e-commerce', 'duracelltomi-google-tag-manager' ),
276
- 'description' => __( 'This feature is deprecated and will be removed soon! You should upgrade to enhanced ecommerce as soon as possible.', 'duracelltomi-google-tag-manager' ),
277
- 'phase' => GTM4WP_PHASE_DEPRECATED
278
- ),
279
- GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC => array(
280
- 'label' => __( 'Track enhanced e-commerce', 'duracelltomi-google-tag-manager' ),
281
- 'description' => sprintf(
282
- __(
283
- 'Choose this option if you would like to track e-commerce data using '.
284
- '<a href="%s" target="_blank">enhanced ecommerce tracking</a>.<br>'.
285
- 'Use the plugin\'s official guides to setup your Google Tag Manager container:<br>'.
286
- '<ul><li><a href="%s" target="_blank">Google Analytics 3 / Universal Analytics setup</a></li>'.
287
- '<li><a href="%s" target="_blank">Google Analytics 4 setup</a></li></ul>'
288
- , 'duracelltomi-google-tag-manager' )
289
- , 'https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce'
290
- , 'https://gtm4wp.com/how-to-articles/how-to-setup-enhanced-ecommerce-tracking'
291
- , 'https://gtm4wp.com/how-to-articles/how-to-setup-enhanced-ecommerce-tracking-google-analytics-4-ga4-version' ),
292
- 'phase' => GTM4WP_PHASE_STABLE,
293
- 'plugintocheck' => 'woocommerce/woocommerce.php',
294
- ),
295
- GTM4WP_OPTION_INTEGRATE_WCPRODPERIMPRESSION => array(
296
- 'label' => __( 'Products per impression', 'duracelltomi-google-tag-manager' ),
297
- 'description' => __(
298
- 'If you have many products shown on product category pages and/or on your site home, you could miss pageviews in Google Analytics due to the ' .
299
- 'amount of data that is needed to be sent. To prevent this, you can split product impression data into multiple Google Analytics events by ' .
300
- 'entering a number here (minimum 10-15 recommended) and adding gtm4wp.productImpressionEEC into your Google Analytics ecommerce event helper ' .
301
- "tag's trigger.<br /><br />Leave this value 0 to include product impression data in your pageview hit.",
302
- 'duracelltomi-google-tag-manager'
303
- ),
304
- 'phase' => GTM4WP_PHASE_STABLE
305
- ),
306
- GTM4WP_OPTION_INTEGRATE_WCEECCARTASFIRSTSTEP => array(
307
- 'label' => __( 'Cart as 1st checkout step', 'duracelltomi-google-tag-manager' ),
308
- 'description' => __( 'Enable this to track the cart page as the first checkout step in enhanced ecommerce instead of the checkout page itself', 'duracelltomi-google-tag-manager' ),
309
- 'phase' => GTM4WP_PHASE_STABLE
310
- ),
311
- GTM4WP_OPTION_INTEGRATE_WCEINCLUDECARTINDL => array(
312
- "label" => __( "Cart content in data layer", 'duracelltomi-google-tag-manager' ),
313
- "description" => __( "Enable this option to include the content of the cart in the data layer on each page. Needs WooCommerce v3.2 or newer. Especially useful for site personalization with Google Optimize.", 'duracelltomi-google-tag-manager' ),
314
- "phase" => GTM4WP_PHASE_STABLE
315
- ),
316
- GTM4WP_OPTION_INTEGRATE_WCUSEFULLCATEGORYPATH => array(
317
- 'label' => __( 'Include full category path.', 'duracelltomi-google-tag-manager' ),
318
- 'description' => __( 'Check this to inclulde the full category path of each product in enhanced ecommerce tracking. WARNING! This can lead to performance issues on large sites with lots of traffic!', 'duracelltomi-google-tag-manager' ),
319
- 'phase' => GTM4WP_PHASE_STABLE
320
- ),
321
- GTM4WP_OPTION_INTEGRATE_WCEECBRANDTAXONOMY => array(
322
- "label" => __( "Taxonomy to be used for product brands", 'duracelltomi-google-tag-manager' ),
323
- "description" => __( "Select which custom taxonomy is being used to add the brand of products", 'duracelltomi-google-tag-manager' ),
324
- "phase" => GTM4WP_PHASE_STABLE
325
- ),
326
- GTM4WP_OPTION_INTEGRATE_WCCUSTOMERDATA => array(
327
- 'label' => __( 'Customer data in data layer', 'duracelltomi-google-tag-manager' ),
328
- 'description' => __( 'Enable this to add all customer data (billing and shipping data, total number of orders and order value) into the data layer (WooCommerce 3.x required)', 'duracelltomi-google-tag-manager' ),
329
- 'phase' => GTM4WP_PHASE_STABLE
330
- ),
331
- GTM4WP_OPTION_INTEGRATE_WCORDERDATA => array(
332
- 'label' => __( 'Order data in data layer', 'duracelltomi-google-tag-manager' ),
333
- 'description' => __( 'Enable this to add all order attribute into the data layer on the order received page regardless and independently from classic and enhanced ecommerce tracking (WooCommerce 3.x required)', 'duracelltomi-google-tag-manager' ),
334
- 'phase' => GTM4WP_PHASE_STABLE
335
- ),
336
- GTM4WP_OPTION_INTEGRATE_WCEXCLUDETAX => array(
337
- 'label' => __( 'Exclude tax from revenue', 'duracelltomi-google-tag-manager' ),
338
- 'description' => __( 'Enable this to exclude tax from the revenue variable while generating the purchase data', 'duracelltomi-google-tag-manager' ),
339
- 'phase' => GTM4WP_PHASE_STABLE
340
- ), GTM4WP_OPTION_INTEGRATE_WCORDERMAXAGE => array(
341
- 'label' => __( 'Only track orders younger than', 'duracelltomi-google-tag-manager' ),
342
- 'description' => __( 'To prevent duplicate transaction tracking at the order received page, enter the maximum age (in minutes) of the order or its payment for the transaction to be measured. Viewing the order received page of older orders will be ignored from transaction tracking, as it is considered to be a measured in an earlier session.', 'duracelltomi-google-tag-manager' ),
343
- 'phase' => GTM4WP_PHASE_EXPERIMENTAL
344
- ),
345
- GTM4WP_OPTION_INTEGRATE_WCEXCLUDESHIPPING => array(
346
- 'label' => __( 'Exclude shipping from revenue', 'duracelltomi-google-tag-manager' ),
347
- 'description' => __( 'Enable this to exclude shipping costs from the revenue variable while generating the purchase data', 'duracelltomi-google-tag-manager' ),
348
- 'phase' => GTM4WP_PHASE_STABLE
349
- ),
350
- GTM4WP_OPTION_INTEGRATE_WCREMARKETING => array(
351
- 'label' => __( 'Google Ads Remarketing', 'duracelltomi-google-tag-manager' ),
352
- 'description' => __( 'Enable this to add Google Ads dynamic remarketing variables to the dataLayer', 'duracelltomi-google-tag-manager' ),
353
- 'phase' => GTM4WP_PHASE_DEPRECATED
354
- ),
355
- GTM4WP_OPTION_INTEGRATE_WCBUSINESSVERTICAL => array(
356
- 'label' => __( 'Google Ads Business Vertical', 'duracelltomi-google-tag-manager' ),
357
- 'description' => sprintf(
358
- __(
359
- 'Select which vertical category to add next to each product to utilize dynamic remarketing for Google Ads.'.
360
- '<br>Use the plugin\'s <a href="%s" target="_blank">official setup guide for dynamic remarketing</a> '.
361
- 'to setup your Google Tag Manager container.'
362
- , 'duracelltomi-google-tag-manager' )
363
- , 'https://gtm4wp.com/how-to-articles/how-to-setup-dynamic-remarketing-in-google-ads-adwords'),
364
- 'phase' => GTM4WP_PHASE_STABLE
365
- ),
366
- GTM4WP_OPTION_INTEGRATE_WCREMPRODIDPREFIX => array(
367
- 'label' => __( 'Product ID prefix', 'duracelltomi-google-tag-manager' ),
368
- 'description' => __( "Some product feed generator plugins prefix product IDs with a fixed text like 'woocommerce_gpf'. You can enter this prefix here so that tags in your website include this prefix as well.", 'duracelltomi-google-tag-manager' ),
369
- 'phase' => GTM4WP_PHASE_STABLE
370
- ),
371
- GTM4WP_OPTION_INTEGRATE_WCUSESKU => array(
372
- 'label' => __( 'Use SKU instead of ID', 'duracelltomi-google-tag-manager' ),
373
- 'description' => __( 'Check this to use product SKU instead of the ID of the products for remarketing and ecommerce tracking. Will fallback to ID if no SKU is set.', 'duracelltomi-google-tag-manager' ),
374
- 'phase' => GTM4WP_PHASE_STABLE
375
- ),
376
- GTM4WP_OPTION_INTEGRATE_WCNOORDERTRACKEDFLAG => array(
377
- 'label' => __( 'Do not flag orders as being tracked', 'duracelltomi-google-tag-manager' ),
378
- 'description' => __(
379
- 'Check this to prevent the plugin to flag orders as being already tracked.<br /><br />This ensures that no order data will be tracked ' .
380
- 'multiple times in any ad or measurement system so please only enable this feature if you really need it (with iDeal you might need this)!',
381
- 'duracelltomi-google-tag-manager'
382
- ),
383
- 'phase' => GTM4WP_PHASE_STABLE
384
- ),
385
-
386
- GTM4WP_OPTION_INTEGRATE_GOOGLEOPTIMIZEIDS => array(
387
- 'label' => __( 'Google Optimize container ID list', 'duracelltomi-google-tag-manager' ),
388
- 'description' => sprintf(
389
- __(
390
- 'Enter a comma separated list of Google Optimize container IDs that you would like to use on your site.<br />' .
391
- 'This plugin will add the <a href="%s">page-hiding snippet</a> to your pages.<br />',
392
- 'duracelltomi-google-tag-manager'
393
- ),
394
- 'https://developers.google.com/optimize/#the_page-hiding_snippet_code'
395
- ) .
396
- '<br /><span class="goid_validation_error">' . __( 'This does not seems to be a valid Google Optimize ID! Valid format: GTM-XXXXXX or OPT-XXXXXX where X can be numbers and capital letters. Use comma without any space (,) to enter multpile IDs.', 'duracelltomi-google-tag-manager' ) . '</span>',
397
- 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
398
- ),
399
- GTM4WP_OPTION_INTEGRATE_GOOGLEOPTIMIZETIMEOUT => array(
400
- 'label' => __( 'Google Optimize page-hiding timeout', 'duracelltomi-google-tag-manager' ),
401
- 'description' => __( 'Enter here the amount of time in milliseconds that the page-hiding snippet should wait before page content gets visible even if Google Optimize has not been completely loaded yet.', 'duracelltomi-google-tag-manager' ),
402
- 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
403
- ),
404
-
405
- GTM4WP_OPTION_INTEGRATE_AMPID => array(
406
- 'label' => __( "Google Tag Manager 'AMP' Container ID", 'duracelltomi-google-tag-manager' ),
407
- 'description' => sprintf( __( 'Enter a comma separated list of Google Tag Manager container IDs that you would like to use on your site. This plugin will add the <a href="%s">AMP GTM snippet</a> to your AMP pages.', 'duracelltomi-google-tag-manager' ), 'https://support.google.com/tagmanager/answer/6103696?hl=en' ) .
408
- '<br /><span class="ampid_validation_error">' . __( 'This does not seems to be a valid Google Tag Manager Container ID! Valid format: GTM-XXXXXX where X can be numbers and capital letters. Use comma without any space (,) to enter multpile IDs.', 'duracelltomi-google-tag-manager' ) . '</span>',
409
- 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
410
- 'plugintocheck' => 'amp/amp.php',
411
- ),
412
-
413
- GTM4WP_OPTION_INTEGRATE_COOKIEBOT => array(
414
- 'label' => __( 'Cookiebot auto blocking', 'duracelltomi-google-tag-manager' ),
415
- 'description' => sprintf( __( 'Enable this checkbox if you wish to use the <a href="%s" target="_blank">automatic cookie blocking mode of Cookiebot with Google Tag Manager</a>.', 'duracelltomi-google-tag-manager' ), 'https://support.cookiebot.com/hc/en-us/articles/360009192739-Google-Tag-Manager-and-Automatic-cookie-blocking' ),
416
- 'phase' => GTM4WP_PHASE_STABLE
417
- ),
418
- );
419
-
420
- $GLOBALS['gtm4wp_advancedfieldtexts'] = array(
421
- GTM4WP_OPTION_DATALAYER_NAME => array(
422
- 'label' => __( 'dataLayer variable name', 'duracelltomi-google-tag-manager' ),
423
- 'description' => __( 'In some cases you need to rename the dataLayer variable. You can enter your name here. Leave black for default name: dataLayer', 'duracelltomi-google-tag-manager' ),
424
- 'phase' => GTM4WP_PHASE_STABLE,
425
- ),
426
- GTM4WP_OPTION_ENV_GTM_AUTH => array(
427
- 'label' => __( 'Environment gtm_auth parameter', 'duracelltomi-google-tag-manager' ),
428
- 'description' => __( 'Enter the gtm_auth parameter of the Google Tag Manager environment that has to be activated on this site. Both gtm_auth and gtm_preview parameters are required to activate the desired environment.', 'duracelltomi-google-tag-manager' ),
429
- 'phase' => GTM4WP_PHASE_STABLE,
430
- ),
431
- GTM4WP_OPTION_ENV_GTM_PREVIEW => array(
432
- 'label' => __( 'Environment gtm_preview parameter', 'duracelltomi-google-tag-manager' ),
433
- 'description' => __( 'Enter the gtm_auth parameter of the Google Tag Manager environment that has to be activated on this site. Both gtm_auth and gtm_preview parameters are required to activate the desired environment.', 'duracelltomi-google-tag-manager' ),
434
- 'phase' => GTM4WP_PHASE_STABLE,
435
- ),
436
- GTM4WP_OPTION_DONOTTRACK => array(
437
- 'label' => __( "Include browser 'Do not track' setting", 'duracelltomi-google-tag-manager' ),
438
- 'description' => __( 'Add into the data layer whether the user has asked not to track any website interaction. You may want to respect this and disable all tags if this variable is set in the data layer.', 'duracelltomi-google-tag-manager' ),
439
- 'phase' => GTM4WP_PHASE_STABLE,
440
- ),
441
- GTM4WP_OPTION_LOADEARLY => array(
442
- 'label' => __( 'Load GTM container as early as possible', 'duracelltomi-google-tag-manager' ),
443
- 'description' => __( "Turning on this option will load your Google Tag Manager container as early as possible during page load. This can cause issues if you are using jQuery in your custom HTML tags that fire on 'Page View' events.", 'duracelltomi-google-tag-manager' ),
444
- 'phase' => GTM4WP_PHASE_STABLE,
445
- ),
446
- GTM4WP_OPTION_GTMDOMAIN => array(
447
- 'label' => __( 'Container domain name', 'duracelltomi-google-tag-manager' ),
448
- 'description' => __( "Enter your custom domain name if you are using a server side GTM container for tracking. Leave this blank to use www.googletagmanager.com", 'duracelltomi-google-tag-manager' ),
449
- 'phase' => GTM4WP_PHASE_STABLE,
450
- )
451
- );
452
-
453
- function gtm4wp_admin_output_section( $args ) {
454
- echo '<span class="tabinfo">';
455
-
456
- switch ( $args['id'] ) {
457
- case GTM4WP_ADMIN_GROUP_GENERAL: {
458
- _e( 'This plugin is intended to be used by IT girls&guys and marketing staff. Please be sure you read the <a href="https://developers.google.com/tag-manager/" target="_blank">Google Tag Manager Help Center</a> before you start using this plugin.<br /><br />', 'duracelltomi-google-tag-manager' );
459
-
460
- break;
461
- }
462
-
463
- case GTM4WP_ADMIN_GROUP_INCLUDES: {
464
- _e( 'Here you can check what data is needed to be included in the dataLayer to be able to access them in Google Tag Manager', 'duracelltomi-google-tag-manager' );
465
- echo '<br />';
466
- printf( __( '* Browser, OS and Device data is provided using <a href="%s">WhichBrowser</a> library.', 'duracelltomi-google-tag-manager' ), 'http://whichbrowser.net/' );
467
-
468
- break;
469
- }
470
-
471
- case GTM4WP_ADMIN_GROUP_EVENTS: {
472
- _e( 'Fire tags in Google Tag Manager on special events on your website', 'duracelltomi-google-tag-manager' );
473
-
474
- break;
475
- }
476
-
477
- case GTM4WP_ADMIN_GROUP_SCROLLER: {
478
- _e( 'Fire tags based on how the visitor scrolls through your page.', 'duracelltomi-google-tag-manager' );
479
- echo '<br />';
480
- printf( __( 'Based on the script originaly posted to <a href="%s">Analytics Talk</a>', 'duracelltomi-google-tag-manager' ), 'http://cutroni.com/blog/2012/02/21/advanced-content-tracking-with-google-analytics-part-1/' );
481
-
482
- break;
483
- }
484
-
485
- case GTM4WP_ADMIN_GROUP_BLACKLIST: {
486
- _e( 'Here you can control which types of tags, triggers and variables can be executed on your site regardless of what tags are included in your container on the Google Tag Manager site. Use this to increase security!', 'duracelltomi-google-tag-manager' );
487
- echo '<br />';
488
- _e( 'Do not modify if you do not know what to do, since it can cause issues with your tag deployment!', 'duracelltomi-google-tag-manager' );
489
- echo '<br />';
490
- _e( 'For example blacklisting everything and only whitelisting the Google Analytics tag without whitelisting the URL variable type will cause your Google Analytics tags to be blocked anyway since the attached triggers (Page View) can not fire!', 'duracelltomi-google-tag-manager' );
491
-
492
- break;
493
- }
494
-
495
- case GTM4WP_ADMIN_GROUP_INTEGRATION: {
496
- _e( 'Google Tag Manager for WordPress can integrate with several popular plugins. Please check the plugins you would like to integrate with:', 'duracelltomi-google-tag-manager' );
497
-
498
- break;
499
- }
500
-
501
- case GTM4WP_ADMIN_GROUP_ADVANCED: {
502
- _e( 'You usually do not need to modify thoose settings. Please be carefull while hacking here.', 'duracelltomi-google-tag-manager' );
503
-
504
- break;
505
- }
506
-
507
- case GTM4WP_ADMIN_GROUP_CREDITS: {
508
- _e( 'Some info about the author of this plugin', 'duracelltomi-google-tag-manager' );
509
-
510
- break;
511
- }
512
- } // end switch
513
-
514
- echo '</span>';
515
- }
516
-
517
- function gtm4wp_admin_output_field( $args ) {
518
- global $gtm4wp_options, $gtm4wp_business_verticals;
519
-
520
- switch ( $args['label_for'] ) {
521
- case GTM4WP_ADMIN_GROUP_GTMID: {
522
- if ( defined( 'GTM4WP_HARDCODED_GTM_ID' ) ) {
523
- $_gtm_id_value = GTM4WP_HARDCODED_GTM_ID;
524
- $_input_readonly = ' readonly="readonly"';
525
- $_warning_after = '<br /><span class="gtm_wpconfig_set">WARNING! Container ID was set and fixed in wp-config.php. If you wish to change this value, please edit your wp-config.php and change the container ID or remove the GTM4WP_HARDCODED_GTM_ID constant!</span>';
526
- } else {
527
- $_gtm_id_value = $gtm4wp_options[ GTM4WP_OPTION_GTM_CODE ];
528
- $_input_readonly = '';
529
- $_warning_after = '';
530
- }
531
-
532
- echo '<input type="text" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_GTM_CODE . ']" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_GTM_CODE . ']" value="' . $_gtm_id_value . '" ' . $_input_readonly . '/><br />' . $args['description'];
533
- echo $_warning_after;
534
- echo '<br /><span class="gtmid_validation_error">' . __( 'This does not seems to be a valid Google Tag Manager ID! Valid format: GTM-XXXXX where X can be numbers and capital letters. Use comma without any space (,) to enter multpile container IDs.', 'duracelltomi-google-tag-manager' ) . '</span>';
535
-
536
- break;
537
- }
538
-
539
- case GTM4WP_ADMIN_GROUP_PLACEMENT: {
540
- echo '<input type="radio" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_GTM_PLACEMENT . ']_' . GTM4WP_PLACEMENT_FOOTER . '" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_GTM_PLACEMENT . ']" value="' . GTM4WP_PLACEMENT_FOOTER . '" ' . ( $gtm4wp_options[ GTM4WP_OPTION_GTM_PLACEMENT ] == GTM4WP_PLACEMENT_FOOTER ? 'checked="checked"' : '' ) . '/> ' . __( 'Footer of the page (not recommended by Google, no tweak in your template required)', 'duracelltomi-google-tag-manager' ) . '<br />';
541
- echo '<input type="radio" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_GTM_PLACEMENT . ']_' . GTM4WP_PLACEMENT_BODYOPEN . '" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_GTM_PLACEMENT . ']" value="' . GTM4WP_PLACEMENT_BODYOPEN . '" ' . ( $gtm4wp_options[ GTM4WP_OPTION_GTM_PLACEMENT ] == GTM4WP_PLACEMENT_BODYOPEN ? 'checked="checked"' : '' ) . '/> ' . __( 'Custom (needs tweak in your template)', 'duracelltomi-google-tag-manager' ) . '<br />';
542
- echo '<input type="radio" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_GTM_PLACEMENT . ']_' . GTM4WP_PLACEMENT_BODYOPEN_AUTO . '" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_GTM_PLACEMENT . ']" value="' . GTM4WP_PLACEMENT_BODYOPEN_AUTO . '" ' . ( $gtm4wp_options[ GTM4WP_OPTION_GTM_PLACEMENT ] == GTM4WP_PLACEMENT_BODYOPEN_AUTO ? 'checked="checked"' : '' ) . '/> ' . __( 'Codeless injection (no tweak, right placement but experimental, could break your frontend)', 'duracelltomi-google-tag-manager' ) . '<br />';
543
- echo '<input type="radio" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_GTM_PLACEMENT . ']_' . GTM4WP_PLACEMENT_OFF . '" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_GTM_PLACEMENT . ']" value="' . GTM4WP_PLACEMENT_OFF . '" ' . ( $gtm4wp_options[ GTM4WP_OPTION_GTM_PLACEMENT ] == GTM4WP_PLACEMENT_OFF ? 'checked="checked"' : '' ) . '/> ' . __( 'Off (only add data layer to the page source)', 'duracelltomi-google-tag-manager' ) . '<br /><br />' . $args['description'];
544
-
545
- break;
546
- }
547
-
548
- case GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_DATALAYER_NAME . ']': {
549
- echo '<input type="text" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_DATALAYER_NAME . ']" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_DATALAYER_NAME . ']" value="' . $gtm4wp_options[ GTM4WP_OPTION_DATALAYER_NAME ] . '" /><br />' . $args['description'];
550
- echo '<br /><span class="datalayername_validation_error">' . __( 'This does not seems to be a valid JavaScript variable name! Please check and try again', 'duracelltomi-google-tag-manager' ) . '</span>';
551
-
552
- break;
553
- }
554
-
555
- case GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_ENV_GTM_AUTH . ']': {
556
- if ( defined( 'GTM4WP_HARDCODED_GTM_ENV_AUTH' ) ) {
557
- $_gtm_auth_value = GTM4WP_HARDCODED_GTM_ENV_AUTH;
558
- $_input_readonly = ' readonly="readonly"';
559
- $_warning_after = '<br /><span class="gtm_wpconfig_set">WARNING! Environment auth parameter was set and fixed in wp-config.php. If you wish to change this value, please edit your wp-config.php and change the parameter value or remove the GTM4WP_HARDCODED_GTM_ENV_AUTH constant!</span>';
560
- } else {
561
- $_gtm_auth_value = $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_AUTH ];
562
- $_input_readonly = '';
563
- $_warning_after = '';
564
- }
565
-
566
- echo '<input type="text" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_ENV_GTM_AUTH . ']" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_ENV_GTM_AUTH . ']" value="' . $_gtm_auth_value . '" ' . $_input_readonly . '/><br />' . $args['description'];
567
- echo $_warning_after;
568
- echo '<br /><span class="gtmauth_validation_error">' . __( 'This does not seems to be a valid gtm_auth parameter! It should only contain letters, number and the &quot;-&quot; character. Please check and try again', 'duracelltomi-google-tag-manager' ) . '</span>';
569
-
570
- break;
571
- }
572
-
573
- case GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_ENV_GTM_PREVIEW . ']': {
574
- if ( defined( 'GTM4WP_HARDCODED_GTM_ENV_PREVIEW' ) ) {
575
- $_gtm_preview_value = GTM4WP_HARDCODED_GTM_ENV_PREVIEW;
576
- $_input_readonly = ' readonly="readonly"';
577
- $_warning_after = '<br /><span class="gtm_wpconfig_set">WARNING! Environment preview parameter was set and fixed in wp-config.php. If you wish to change this value, please edit your wp-config.php and change the parameter value or remove the GTM4WP_HARDCODED_GTM_ENV_PREVIEW constant!</span>';
578
- } else {
579
- $_gtm_preview_value = $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_PREVIEW ];
580
- $_input_readonly = '';
581
- $_warning_after = '';
582
- }
583
-
584
- echo '<input type="text" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_ENV_GTM_PREVIEW . ']" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_ENV_GTM_PREVIEW . ']" value="' . $_gtm_preview_value . '" ' . $_input_readonly . '/><br />' . $args['description'];
585
- echo $_warning_after;
586
- echo '<br /><span class="gtmpreview_validation_error">' . __( 'This does not seems to be a valid gtm_preview parameter! It should have the format &quot;env-NN&quot; where NN is an integer number. Please check and try again', 'duracelltomi-google-tag-manager' ) . '</span>';
587
-
588
- break;
589
- }
590
-
591
- case GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_BLACKLIST_ENABLE . ']': {
592
- echo '<input type="radio" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_BLACKLIST_ENABLE . ']_0" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_BLACKLIST_ENABLE . ']" value="0" ' . ( $gtm4wp_options[ GTM4WP_OPTION_BLACKLIST_ENABLE ] == 0 ? 'checked="checked"' : '' ) . '/> ' . __( 'Disable feature: control everything on Google Tag Manager interface', 'duracelltomi-google-tag-manager' ) . '<br />';
593
- echo '<input type="radio" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_BLACKLIST_ENABLE . ']_1" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_BLACKLIST_ENABLE . ']" value="1" ' . ( $gtm4wp_options[ GTM4WP_OPTION_BLACKLIST_ENABLE ] == 1 ? 'checked="checked"' : '' ) . '/> ' . __( 'Allow all, except the checked items on all blacklist tabs (blacklist)', 'duracelltomi-google-tag-manager' ) . '<br />';
594
- echo '<input type="radio" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_BLACKLIST_ENABLE . ']_2" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_BLACKLIST_ENABLE . ']" value="2" ' . ( $gtm4wp_options[ GTM4WP_OPTION_BLACKLIST_ENABLE ] == 2 ? 'checked="checked"' : '' ) . '/> ' . __( 'Block all, except the checked items on all blacklist tabs (whitelist)', 'duracelltomi-google-tag-manager' ) . '<br />';
595
- echo $args['description'];
596
-
597
- break;
598
- }
599
-
600
- case GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_INCLUDE_WEATHERUNITS . ']': {
601
- echo '<input type="radio" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_INCLUDE_WEATHERUNITS . ']_0" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_INCLUDE_WEATHERUNITS . ']" value="0" ' . ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_WEATHERUNITS ] == 0 ? 'checked="checked"' : '' ) . '/> ' . __( 'Celsius', 'duracelltomi-google-tag-manager' ) . '<br />';
602
- echo '<input type="radio" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_INCLUDE_WEATHERUNITS . ']_1" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_INCLUDE_WEATHERUNITS . ']" value="1" ' . ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_WEATHERUNITS ] == 1 ? 'checked="checked"' : '' ) . '/> ' . __( 'Fahrenheit', 'duracelltomi-google-tag-manager' ) . '<br />';
603
- echo $args['description'];
604
-
605
- break;
606
- }
607
-
608
- case GTM4WP_ADMIN_GROUP_INFO: {
609
- echo $args['description'];
610
-
611
- break;
612
- }
613
-
614
- case GTM4WP_OPTIONS . "[" . GTM4WP_OPTION_INTEGRATE_WCEECBRANDTAXONOMY . "]": {
615
- echo '<select id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_INTEGRATE_WCEECBRANDTAXONOMY . ']" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_INTEGRATE_WCEECBRANDTAXONOMY . ']">';
616
- echo '<option value="">(not set)</option>';
617
-
618
- $gtm4wp_taxonomies = get_taxonomies(array(
619
- "show_ui" => true,
620
- "public" => true,
621
- "_builtin" => false
622
- ), "object", "and");
623
-
624
- foreach( $gtm4wp_taxonomies as $onetaxonomy ) {
625
- echo '<option value="' . $onetaxonomy->name . '"' . ( $gtm4wp_options[GTM4WP_OPTION_INTEGRATE_WCEECBRANDTAXONOMY] === $onetaxonomy->name ? ' selected="selected"' : '' ) . '>' . $onetaxonomy->label . '</option>';
626
- }
627
-
628
- echo '</select>';
629
-
630
- break;
631
- }
632
-
633
- case GTM4WP_OPTIONS . "[" . GTM4WP_OPTION_INTEGRATE_WCBUSINESSVERTICAL . "]": {
634
- echo '<select id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_INTEGRATE_WCBUSINESSVERTICAL . ']" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_INTEGRATE_WCBUSINESSVERTICAL . ']">';
635
-
636
- foreach( $gtm4wp_business_verticals as $vertical_id => $vertical_display_name ) {
637
- echo '<option value="' . $vertical_id . '"' . ( $gtm4wp_options[GTM4WP_OPTION_INTEGRATE_WCBUSINESSVERTICAL] === $vertical_id ? ' selected="selected"' : '' ) . '>' . $vertical_display_name . '</option>';
638
- }
639
-
640
- echo '</select><br>' . $args['description'];
641
-
642
- break;
643
- }
644
-
645
- default: {
646
- if ( preg_match( '/' . GTM4WP_OPTIONS . "\\[blacklist\\-[^\\]]+\\]/i", $args['label_for'] ) ) {
647
- if ( 'blacklist-sandboxed' == $args['entityid'] ) {
648
- echo '<input type="checkbox" id="' . $args['label_for'] . '" name="' . $args['label_for'] . '" value="1" ' . checked( 1, $gtm4wp_options[ GTM4WP_OPTION_BLACKLIST_SANDBOXED ], false ) . ' /><br />' . $args['description'];
649
- } else {
650
- echo '<input type="checkbox" id="' . $args['label_for'] . '" name="' . $args['label_for'] . '" value="1" ' . checked( 1, in_array( $args['entityid'], $gtm4wp_options[ GTM4WP_OPTION_BLACKLIST_STATUS ] ), false ) . ' /><br />' . $args['description'];
651
- }
652
- } else {
653
- $optval = $gtm4wp_options[ $args['optionfieldid'] ];
654
-
655
- switch ( gettype( $optval ) ) {
656
- case 'boolean': {
657
- echo '<input type="checkbox" id="' . GTM4WP_OPTIONS . '[' . $args['optionfieldid'] . ']" name="' . GTM4WP_OPTIONS . '[' . $args['optionfieldid'] . ']" value="1" ' . checked( 1, $optval, false ) . ' /><br />' . $args['description'];
658
-
659
- if ( isset( $args['plugintocheck'] ) && ( $args['plugintocheck'] != '' ) ) {
660
- if ( is_plugin_active( $args['plugintocheck'] ) ) {
661
- echo '<br />' . __( 'This plugin is <strong class="gtm4wp-plugin-active">active</strong>, it is strongly recommended to enable this integration!', 'duracelltomi-google-tag-manager' );
662
- } else {
663
- echo '<br />' . __( 'This plugin (' . $args['plugintocheck'] . ') is <strong class="gtm4wp-plugin-not-active">not active</strong>, enabling this integration could cause issues on frontend!', 'duracelltomi-google-tag-manager' );
664
- }
665
- }
666
-
667
- break;
668
- }
669
-
670
- case 'integer': {
671
- echo '<input type="number" step="1" min="0" class="small-text" id="' . GTM4WP_OPTIONS . '[' . $args['optionfieldid'] . ']" name="' . GTM4WP_OPTIONS . '[' . $args['optionfieldid'] . ']" value="' . esc_attr( $optval ) . '" /><br />' . $args['description'];
672
-
673
- if ( isset( $args['plugintocheck'] ) && ( $args['plugintocheck'] != '' ) ) {
674
- if ( is_plugin_active( $args['plugintocheck'] ) ) {
675
- echo '<br />' . __( 'This plugin is <strong class="gtm4wp-plugin-active">active</strong>, it is strongly recommended to enable this integration!', 'duracelltomi-google-tag-manager' );
676
- } else {
677
- echo '<br />' . __( 'This plugin is <strong class="gtm4wp-plugin-not-active">not active</strong>, enabling this integration could cause issues on frontend!', 'duracelltomi-google-tag-manager' );
678
- }
679
- }
680
-
681
- break;
682
- }
683
-
684
- default : {
685
- echo '<input type="text" id="' . GTM4WP_OPTIONS . '[' . $args['optionfieldid'] . ']" name="' . GTM4WP_OPTIONS . '[' . $args['optionfieldid'] . ']" value="' . esc_attr( $optval ) . '" size="80" /><br />' . $args['description'];
686
-
687
- if ( isset( $args['plugintocheck'] ) && ( $args['plugintocheck'] != '' ) ) {
688
- if ( is_plugin_active( $args['plugintocheck'] ) ) {
689
- echo '<br />' . __( 'This plugin is <strong class="gtm4wp-plugin-active">active</strong>, it is strongly recommended to enable this integration!', 'duracelltomi-google-tag-manager' );
690
- } else {
691
- echo '<br />' . __( 'This plugin is <strong class="gtm4wp-plugin-not-active">not active</strong>, enabling this integration could cause issues on frontend!', 'duracelltomi-google-tag-manager' );
692
- }
693
- }
694
- }
695
- } // end switch gettype optval
696
- }
697
- }
698
- } // end switch
699
- }
700
-
701
- function gtm4wp_sanitize_options( $options ) {
702
- global $wpdb, $gtm4wp_entity_ids;
703
-
704
- $output = gtm4wp_reload_options();
705
-
706
- foreach ( $output as $optionname => $optionvalue ) {
707
- if ( isset( $options[ $optionname ] ) ) {
708
- $newoptionvalue = $options[ $optionname ];
709
- } else {
710
- $newoptionvalue = '';
711
- }
712
-
713
- // "include" settings
714
- if ( substr( $optionname, 0, 8 ) == 'include-' ) {
715
- $output[ $optionname ] = (bool) $newoptionvalue;
716
-
717
- // dataLayer events
718
- } elseif ( substr( $optionname, 0, 6 ) == 'event-' ) {
719
- $output[ $optionname ] = (bool) $newoptionvalue;
720
-
721
- // clear oembed transients when feature is enabled because we need to hook into the oembed process to enable some 3rd party APIs
722
- if ( $output[ $optionname ] && ! $optionvalue ) {
723
- if ( GTM4WP_OPTION_EVENTS_YOUTUBE == $optionname ) {
724
- $wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_value LIKE '%youtube.com%' AND meta_key LIKE '_oembed_%'" );
725
- }
726
-
727
- if ( GTM4WP_OPTION_EVENTS_VIMEO == $optionname ) {
728
- $wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_value LIKE '%vimeo.com%' AND meta_key LIKE '_oembed_%'" );
729
- }
730
- }
731
-
732
- // blacklist / whitelist entities
733
- } elseif ( substr( $optionname, 0, 10 ) == 'blacklist-' ) {
734
- if ( GTM4WP_OPTION_BLACKLIST_ENABLE === $optionname ) {
735
- $output[ $optionname ] = (int) $options[ GTM4WP_OPTION_BLACKLIST_ENABLE ];
736
- } else if ( GTM4WP_OPTION_BLACKLIST_SANDBOXED == $optionname ) {
737
- $output[ $optionname ] = (bool) $newoptionvalue;
738
- } else if ( GTM4WP_OPTION_BLACKLIST_STATUS == $optionname ) {
739
- $selected_blacklist_entities = array();
740
-
741
- foreach( $gtm4wp_entity_ids as $gtm_entity_group_id => $gtm_entity_group_list ) {
742
- foreach( $gtm_entity_group_list as $gtm_entity_id => $gtm_entity_label ) {
743
- $entity_option_id = 'blacklist-' . $gtm_entity_group_id . '-' . $gtm_entity_id;
744
- if ( array_key_exists( $entity_option_id, $options ) ) {
745
- $newoptionvalue = (bool) $options[ $entity_option_id ];
746
- if ( $newoptionvalue ) {
747
- $selected_blacklist_entities[] = $gtm_entity_id;
748
- }
749
- }
750
- }
751
- }
752
-
753
- $output[ $optionname ] = implode( ',', $selected_blacklist_entities );
754
- }
755
-
756
- // Google Optimize settings
757
- } elseif ( $optionname == GTM4WP_OPTION_INTEGRATE_GOOGLEOPTIMIZEIDS ) {
758
- $_goid_val = trim( $newoptionvalue );
759
- if ( '' == $_goid_val ) {
760
- $_goid_list = array();
761
- } else {
762
- $_goid_list = explode( ',', $_goid_val );
763
- }
764
- $_goid_haserror = false;
765
-
766
- foreach ( $_goid_list as $one_go_id ) {
767
- $_goid_haserror = $_goid_haserror || ! preg_match( '/^(GTM|OPT)-[A-Z0-9]+$/', $one_go_id );
768
- }
769
-
770
- if ( $_goid_haserror && ( count( $_goid_list ) > 0 ) ) {
771
- add_settings_error( GTM4WP_ADMIN_GROUP, GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_INTEGRATE_GOOGLEOPTIMIZEIDS . ']', __( 'Invalid Google Optimize ID. Valid ID format: GTM-XXXXX or OPT-XXXXX. Use comma without additional space (,) to enter more than one ID.', 'duracelltomi-google-tag-manager' ) );
772
- } else {
773
- $output[ $optionname ] = $newoptionvalue;
774
- }
775
- } elseif ( $optionname == GTM4WP_OPTION_INTEGRATE_GOOGLEOPTIMIZETIMEOUT ) {
776
- $output[ $optionname ] = (int) $newoptionvalue;
777
-
778
- } elseif ( $optionname == GTM4WP_OPTION_INTEGRATE_WCPRODPERIMPRESSION ) {
779
- $output[ $optionname ] = (int) $newoptionvalue;
780
-
781
- } elseif ( $optionname == GTM4WP_OPTION_INTEGRATE_WCORDERMAXAGE ) {
782
- $output[ $optionname ] = (int) $newoptionvalue;
783
-
784
- }elseif ( $optionname == GTM4WP_OPTION_INTEGRATE_WCREMPRODIDPREFIX ) {
785
- $output[ $optionname ] = trim( (string) $newoptionvalue );
786
-
787
- } else if ( $optionname == GTM4WP_OPTION_INTEGRATE_WCEECBRANDTAXONOMY ) {
788
- $output[$optionname] = trim( (string) $newoptionvalue );
789
-
790
- } else if ( $optionname == GTM4WP_OPTION_INTEGRATE_WCBUSINESSVERTICAL ) {
791
- $output[$optionname] = trim( (string) $newoptionvalue );
792
-
793
- } else if ( $optionname == GTM4WP_OPTION_GTMDOMAIN ) {
794
- // for PHP 7- compatibility
795
- if ( !defined("FILTER_FLAG_HOSTNAME") ) {
796
- define( "FILTER_FLAG_HOSTNAME", 0 );
797
- }
798
-
799
- $newoptionvalue = filter_var( $newoptionvalue, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME );
800
- if ( $newoptionvalue === false ) {
801
- $newoptionvalue = '';
802
- }
803
- $output[$optionname] = trim( (string) $newoptionvalue );
804
-
805
- // Accelerated Mobile Pages settings
806
- } elseif ( $optionname == GTM4WP_OPTION_INTEGRATE_AMPID ) {
807
- $_ampid_val = trim( $newoptionvalue );
808
- if ( '' == $_ampid_val ) {
809
- $_ampid_list = array();
810
- } else {
811
- $_ampid_list = explode( ',', $_ampid_val );
812
- }
813
- $_ampid_haserror = false;
814
-
815
- foreach ( $_ampid_list as $one_amp_id ) {
816
- $_ampid_haserror = $_ampid_haserror || ! preg_match( '/^GTM-[A-Z0-9]+$/', $one_amp_id );
817
- }
818
-
819
- if ( $_ampid_haserror && ( count( $_ampid_list ) > 0 ) ) {
820
- add_settings_error( GTM4WP_ADMIN_GROUP, GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_INTEGRATE_AMPID . ']', __( 'Invalid AMP Google Tag Manager Container ID. Valid ID format: GTM-XXXXX. Use comma without additional space (,) to enter more than one ID.', 'duracelltomi-google-tag-manager' ) );
821
- } else {
822
- $output[ $optionname ] = $newoptionvalue;
823
- }
824
-
825
- // integrations
826
- } elseif ( substr( $optionname, 0, 10 ) == 'integrate-' ) {
827
- $output[ $optionname ] = (bool) $newoptionvalue;
828
-
829
- // GTM code or dataLayer variable name
830
- } elseif ( ( $optionname == GTM4WP_OPTION_GTM_CODE ) || ( $optionname == GTM4WP_OPTION_DATALAYER_NAME ) || ( $optionname == GTM4WP_OPTION_ENV_GTM_AUTH ) || ( $optionname == GTM4WP_OPTION_ENV_GTM_PREVIEW ) ) {
831
- $newoptionvalue = trim( $newoptionvalue );
832
-
833
- if ( $optionname == GTM4WP_OPTION_GTM_CODE ) {
834
- $_gtmid_list = explode( ',', $newoptionvalue );
835
- $_gtmid_haserror = false;
836
-
837
- foreach ( $_gtmid_list as $one_gtm_id ) {
838
- $_gtmid_haserror = $_gtmid_haserror || ! preg_match( '/^GTM-[A-Z0-9]+$/', $one_gtm_id );
839
- }
840
-
841
- if ( $_gtmid_haserror ) {
842
- add_settings_error( GTM4WP_ADMIN_GROUP, GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_GTM_CODE . ']', __( 'Invalid Google Tag Manager ID. Valid ID format: GTM-XXXXX. Use comma without additional space (,) to enter more than one container ID.', 'duracelltomi-google-tag-manager' ) );
843
- } else {
844
- $output[ $optionname ] = $newoptionvalue;
845
- }
846
- } elseif ( ( $optionname == GTM4WP_OPTION_DATALAYER_NAME ) && ( $newoptionvalue != '' ) && ( ! preg_match( '/^[a-zA-Z][a-zA-Z0-9_-]*$/', $newoptionvalue ) ) ) {
847
- add_settings_error( GTM4WP_ADMIN_GROUP, GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_DATALAYER_NAME . ']', __( "Invalid dataLayer variable name. Please start with a character from a-z or A-Z followed by characters from a-z, A-Z, 0-9 or '_' or '-'!", 'duracelltomi-google-tag-manager' ) );
848
-
849
- } elseif ( ( $optionname == GTM4WP_OPTION_ENV_GTM_AUTH ) && ( $newoptionvalue != '' ) && ( ! preg_match( '/^[a-zA-Z0-9-_]+$/', $newoptionvalue ) ) ) {
850
- add_settings_error( GTM4WP_ADMIN_GROUP, GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_ENV_GTM_AUTH . ']', __( "Invalid gtm_auth environment parameter value. It should only contain letters, numbers or the '-' and '_' characters.", 'duracelltomi-google-tag-manager' ) );
851
-
852
- } elseif ( ( $optionname == GTM4WP_OPTION_ENV_GTM_PREVIEW ) && ( $newoptionvalue != '' ) && ( ! preg_match( '/^env-[0-9]+$/', $newoptionvalue ) ) ) {
853
- add_settings_error( GTM4WP_ADMIN_GROUP, GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_ENV_GTM_PREVIEW . ']', __( "Invalid gtm_preview environment parameter value. It should have the format 'env-NN' where NN is an integer number.", 'duracelltomi-google-tag-manager' ) );
854
-
855
- } else {
856
- $output[ $optionname ] = $newoptionvalue;
857
- }
858
-
859
- // GTM container code placement
860
- } elseif ( $optionname == GTM4WP_OPTION_GTM_PLACEMENT ) {
861
- $output[ $optionname ] = (int) $newoptionvalue;
862
- if ( ( $output[ $optionname ] < 0 ) || ( $output[ $optionname ] > 3 ) ) {
863
- $output[ $optionname ] = 0;
864
- }
865
-
866
- // scroll tracking content ID
867
- } elseif ( $optionname == GTM4WP_OPTION_SCROLLER_CONTENTID ) {
868
- $output[ $optionname ] = trim( str_replace( '#', '', $newoptionvalue ) );
869
-
870
- // anything else
871
- } else {
872
- switch ( gettype( $optionvalue ) ) {
873
- case 'boolean': {
874
- $output[ $optionname ] = (bool) $newoptionvalue;
875
-
876
- break;
877
- }
878
-
879
- case 'integer': {
880
- $output[ $optionname ] = (int) $newoptionvalue;
881
-
882
- break;
883
- }
884
-
885
- default: {
886
- $output[ $optionname ] = $newoptionvalue;
887
- }
888
- } // end switch
889
- }
890
- }
891
-
892
- return $output;
893
- }
894
-
895
- function gtm4wp_admin_init() {
896
- global $gtm4wp_includefieldtexts, $gtm4wp_eventfieldtexts, $gtm4wp_integratefieldtexts, $gtm4wp_scrollerfieldtexts,
897
- $gtm4wp_advancedfieldtexts, $gtm4wp_entity_ids;
898
-
899
- register_setting( GTM4WP_ADMIN_GROUP, GTM4WP_OPTIONS, 'gtm4wp_sanitize_options' );
900
-
901
- add_settings_section(
902
- GTM4WP_ADMIN_GROUP_GENERAL,
903
- __( 'General', 'duracelltomi-google-tag-manager' ),
904
- 'gtm4wp_admin_output_section',
905
- GTM4WP_ADMINSLUG
906
- );
907
-
908
- add_settings_field(
909
- GTM4WP_ADMIN_GROUP_GTMID,
910
- __( 'Google Tag Manager ID', 'duracelltomi-google-tag-manager' ),
911
- 'gtm4wp_admin_output_field',
912
- GTM4WP_ADMINSLUG,
913
- GTM4WP_ADMIN_GROUP_GENERAL,
914
- array(
915
- 'label_for' => GTM4WP_ADMIN_GROUP_GTMID,
916
- 'description' => __( 'Enter your Google Tag Manager ID here. Use comma without space (,) to enter multiple IDs.', 'duracelltomi-google-tag-manager' ),
917
- )
918
- );
919
-
920
- add_settings_field(
921
- GTM4WP_ADMIN_GROUP_PLACEMENT,
922
- __( 'Container code <code>&lt;noscript&gt;</code> part placement', 'duracelltomi-google-tag-manager' ),
923
- 'gtm4wp_admin_output_field',
924
- GTM4WP_ADMINSLUG,
925
- GTM4WP_ADMIN_GROUP_GENERAL,
926
- array(
927
- 'label_for' => GTM4WP_ADMIN_GROUP_PLACEMENT,
928
- 'description' => __( "Code placement decides where to put the second, so called noscript part of the GTM container code.<br />This code is usually only executed if your visitor has for some reason disabled JavaScript.<br/>The main GTM container code will be placed into the <code>&lt;head&gt;</code> section of your webpages anyway (where it belongs to).<br />If you select 'Custom' you need to edit your template file and add the following line just after the opening <code>&lt;body&gt;</code> tag:<br /><code>&lt;?php if ( function_exists( 'gtm4wp_the_gtm_tag' ) ) { gtm4wp_the_gtm_tag(); } ?&gt;</code>", 'duracelltomi-google-tag-manager' ),
929
- )
930
- );
931
-
932
- add_settings_section(
933
- GTM4WP_ADMIN_GROUP_INCLUDES,
934
- __( 'Basic data', 'duracelltomi-google-tag-manager' ),
935
- 'gtm4wp_admin_output_section',
936
- GTM4WP_ADMINSLUG
937
- );
938
-
939
- foreach ( $gtm4wp_includefieldtexts as $fieldid => $fielddata ) {
940
- $phase = isset( $fielddata['phase'] ) ? $fielddata['phase'] : GTM4WP_PHASE_STABLE;
941
-
942
- add_settings_field(
943
- 'gtm4wp-admin-' . $fieldid . '-id',
944
- $fielddata['label'] . '<span class="' . $phase . '"></span>',
945
- 'gtm4wp_admin_output_field',
946
- GTM4WP_ADMINSLUG,
947
- GTM4WP_ADMIN_GROUP_INCLUDES,
948
- array(
949
- 'label_for' => 'gtm4wp-options[' . $fieldid . ']',
950
- 'description' => $fielddata['description'],
951
- 'optionfieldid' => $fieldid,
952
- )
953
- );
954
- }
955
-
956
- add_settings_section(
957
- GTM4WP_ADMIN_GROUP_EVENTS,
958
- __( 'Events', 'duracelltomi-google-tag-manager' ),
959
- 'gtm4wp_admin_output_section',
960
- GTM4WP_ADMINSLUG
961
- );
962
-
963
- foreach ( $gtm4wp_eventfieldtexts as $fieldid => $fielddata ) {
964
- $phase = isset( $fielddata['phase'] ) ? $fielddata['phase'] : GTM4WP_PHASE_STABLE;
965
-
966
- add_settings_field(
967
- 'gtm4wp-admin-' . $fieldid . '-id',
968
- $fielddata['label'] . '<span class="' . $phase . '"></span>',
969
- 'gtm4wp_admin_output_field',
970
- GTM4WP_ADMINSLUG,
971
- GTM4WP_ADMIN_GROUP_EVENTS,
972
- array(
973
- 'label_for' => 'gtm4wp-options[' . $fieldid . ']',
974
- 'description' => $fielddata['description'],
975
- 'optionfieldid' => $fieldid,
976
- )
977
- );
978
- }
979
-
980
- add_settings_section(
981
- GTM4WP_ADMIN_GROUP_SCROLLER,
982
- __( 'Scroll tracking', 'duracelltomi-google-tag-manager' ),
983
- 'gtm4wp_admin_output_section',
984
- GTM4WP_ADMINSLUG
985
- );
986
-
987
- foreach ( $gtm4wp_scrollerfieldtexts as $fieldid => $fielddata ) {
988
- $phase = isset( $fielddata['phase'] ) ? $fielddata['phase'] : GTM4WP_PHASE_STABLE;
989
-
990
- add_settings_field(
991
- 'gtm4wp-admin-' . $fieldid . '-id',
992
- $fielddata['label'] . '<span class="' . $phase . '"></span>',
993
- 'gtm4wp_admin_output_field',
994
- GTM4WP_ADMINSLUG,
995
- GTM4WP_ADMIN_GROUP_SCROLLER,
996
- array(
997
- 'label_for' => 'gtm4wp-options[' . $fieldid . ']',
998
- 'description' => $fielddata['description'],
999
- 'optionfieldid' => $fieldid,
1000
- )
1001
- );
1002
- }
1003
-
1004
- add_settings_section(
1005
- GTM4WP_ADMIN_GROUP_BLACKLIST,
1006
- __( 'Security', 'duracelltomi-google-tag-manager' ),
1007
- 'gtm4wp_admin_output_section',
1008
- GTM4WP_ADMINSLUG
1009
- );
1010
-
1011
- add_settings_field(
1012
- GTM4WP_OPTION_BLACKLIST_ENABLE,
1013
- __( 'Enable blacklist/whitelist', 'duracelltomi-google-tag-manager' ),
1014
- 'gtm4wp_admin_output_field',
1015
- GTM4WP_ADMINSLUG,
1016
- GTM4WP_ADMIN_GROUP_BLACKLIST,
1017
- array(
1018
- 'label_for' => GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_BLACKLIST_ENABLE . ']',
1019
- 'description' => '',
1020
- 'optionsfieldid' => GTM4WP_OPTION_BLACKLIST_ENABLE
1021
- )
1022
- );
1023
-
1024
- add_settings_field(
1025
- GTM4WP_OPTION_BLACKLIST_SANDBOXED,
1026
- __( 'Custom tag/variable templates', 'duracelltomi-google-tag-manager' ),
1027
- 'gtm4wp_admin_output_field',
1028
- GTM4WP_ADMINSLUG,
1029
- GTM4WP_ADMIN_GROUP_BLACKLIST,
1030
- array(
1031
- 'label_for' => GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_BLACKLIST_SANDBOXED . ']',
1032
- 'description' => '',
1033
- 'entityid' => GTM4WP_OPTION_BLACKLIST_SANDBOXED
1034
- )
1035
- );
1036
-
1037
- foreach( $gtm4wp_entity_ids as $gtm_entity_group_id => $gtm_entity_group_list ) {
1038
- foreach( $gtm_entity_group_list as $gtm_entity_id => $gtm_entity_label ) {
1039
- add_settings_field(
1040
- 'gtm4wp-admin-blacklist-' . $gtm_entity_group_id . '-' . $gtm_entity_id . '-id',
1041
- $gtm_entity_label,
1042
- 'gtm4wp_admin_output_field',
1043
- GTM4WP_ADMINSLUG,
1044
- GTM4WP_ADMIN_GROUP_BLACKLIST,
1045
- array(
1046
- 'label_for' => 'gtm4wp-options[blacklist-' . $gtm_entity_group_id . '-' . $gtm_entity_id . ']',
1047
- 'description' => '',
1048
- 'entityid' => $gtm_entity_id,
1049
- )
1050
- );
1051
- }
1052
- }
1053
-
1054
- add_settings_section(
1055
- GTM4WP_ADMIN_GROUP_INTEGRATION,
1056
- __( 'Integration', 'duracelltomi-google-tag-manager' ),
1057
- 'gtm4wp_admin_output_section',
1058
- GTM4WP_ADMINSLUG
1059
- );
1060
-
1061
- foreach ( $gtm4wp_integratefieldtexts as $fieldid => $fielddata ) {
1062
- $phase = isset( $fielddata['phase'] ) ? $fielddata['phase'] : GTM4WP_PHASE_STABLE;
1063
-
1064
- add_settings_field(
1065
- 'gtm4wp-admin-' . $fieldid . '-id',
1066
- $fielddata['label'] . '<span class="' . $phase . '"></span>',
1067
- 'gtm4wp_admin_output_field',
1068
- GTM4WP_ADMINSLUG,
1069
- GTM4WP_ADMIN_GROUP_INTEGRATION,
1070
- array(
1071
- 'label_for' => 'gtm4wp-options[' . $fieldid . ']',
1072
- 'description' => $fielddata['description'],
1073
- 'optionfieldid' => $fieldid,
1074
- 'plugintocheck' => isset( $fielddata['plugintocheck'] ) ? $fielddata['plugintocheck'] : '',
1075
- )
1076
- );
1077
- }
1078
-
1079
- add_settings_section(
1080
- GTM4WP_ADMIN_GROUP_ADVANCED,
1081
- __( 'Advanced', 'duracelltomi-google-tag-manager' ),
1082
- 'gtm4wp_admin_output_section',
1083
- GTM4WP_ADMINSLUG
1084
- );
1085
-
1086
- foreach ( $gtm4wp_advancedfieldtexts as $fieldid => $fielddata ) {
1087
- $phase = isset( $fielddata['phase'] ) ? $fielddata['phase'] : GTM4WP_PHASE_STABLE;
1088
-
1089
- add_settings_field(
1090
- 'gtm4wp-admin-' . $fieldid . '-id',
1091
- $fielddata['label'] . '<span class="' . $phase . '"></span>',
1092
- 'gtm4wp_admin_output_field',
1093
- GTM4WP_ADMINSLUG,
1094
- GTM4WP_ADMIN_GROUP_ADVANCED,
1095
- array(
1096
- 'label_for' => 'gtm4wp-options[' . $fieldid . ']',
1097
- 'description' => $fielddata['description'],
1098
- 'optionfieldid' => $fieldid,
1099
- 'plugintocheck' => isset( $fielddata['plugintocheck'] ) ? $fielddata['plugintocheck'] : '',
1100
- )
1101
- );
1102
- }
1103
-
1104
- add_settings_section(
1105
- GTM4WP_ADMIN_GROUP_CREDITS,
1106
- __( 'Credits', 'duracelltomi-google-tag-manager' ),
1107
- 'gtm4wp_admin_output_section',
1108
- GTM4WP_ADMINSLUG
1109
- );
1110
-
1111
- add_settings_field(
1112
- GTM4WP_ADMIN_GROUP_INFO,
1113
- __( 'Author', 'duracelltomi-google-tag-manager' ),
1114
- 'gtm4wp_admin_output_field',
1115
- GTM4WP_ADMINSLUG,
1116
- GTM4WP_ADMIN_GROUP_CREDITS,
1117
- array(
1118
- 'label_for' => GTM4WP_ADMIN_GROUP_INFO,
1119
- 'description' => '<strong>Thomas Geiger</strong><br />
1120
- Website: <a href="https://gtm4wp.com/" target="_blank">gtm4wp.com</a><br />
1121
- <a href="https://www.linkedin.com/in/duracelltomi" target="_blank">Me on LinkedIn</a><br />
1122
- <a href="http://www.linkedin.com/company/jabjab-online-marketing-ltd" target="_blank">JabJab Online Marketing on LinkedIn</a>',
1123
- )
1124
- );
1125
-
1126
- // apply oembed code changes on the admin as well since the oembed call on the admin is cached by WordPress into a transient
1127
- // that is applied on the frontend later
1128
- require_once dirname( __FILE__ ) . '/../integration/youtube.php';
1129
- require_once dirname( __FILE__ ) . '/../integration/vimeo.php';
1130
- require_once dirname( __FILE__ ) . '/../integration/soundcloud.php';
1131
- }
1132
-
1133
- function gtm4wp_show_admin_page() {
1134
- global $gtp4wp_plugin_url;
1135
- ?>
1136
- <div class="wrap">
1137
- <div id="gtm4wp-icon" class="icon32" style="background-image: url(<?php echo $gtp4wp_plugin_url; ?>admin/images/tag_manager-32.png);"><br /></div>
1138
- <h2><?php _e( 'Google Tag Manager for WordPress options', 'duracelltomi-google-tag-manager' ); ?></h2>
1139
- <form action="options.php" method="post">
1140
- <?php settings_fields( GTM4WP_ADMIN_GROUP ); ?>
1141
- <?php do_settings_sections( GTM4WP_ADMINSLUG ); ?>
1142
- <?php submit_button(); ?>
1143
-
1144
- </form>
1145
- </div>
1146
- <?php
1147
- }
1148
-
1149
- function gtm4wp_add_admin_page() {
1150
- add_options_page(
1151
- __( 'Google Tag Manager for WordPress settings', 'duracelltomi-google-tag-manager' ),
1152
- __( 'Google Tag Manager', 'duracelltomi-google-tag-manager' ),
1153
- 'manage_options',
1154
- GTM4WP_ADMINSLUG,
1155
- 'gtm4wp_show_admin_page'
1156
- );
1157
- }
1158
-
1159
- function gtm4wp_add_admin_js( $hook ) {
1160
- global $gtp4wp_plugin_url;
1161
-
1162
- if ( $hook == 'settings_page_' . GTM4WP_ADMINSLUG ) {
1163
- wp_register_script( 'admin-subtabs', $gtp4wp_plugin_url . 'js/admin-subtabs.js', array(), GTM4WP_VERSION );
1164
-
1165
- $subtabtexts = array(
1166
- 'posttabtitle' => __( 'Posts', 'duracelltomi-google-tag-manager' ),
1167
- 'searchtabtitle' => __( 'Search', 'duracelltomi-google-tag-manager' ),
1168
- 'visitortabtitle' => __( 'Visitors', 'duracelltomi-google-tag-manager' ),
1169
- 'adwordstabtitle' => __( 'Google Ads', 'duracelltomi-google-tag-manager' ),
1170
- 'browsertabtitle' => __( 'Browser/OS/Device', 'duracelltomi-google-tag-manager' ),
1171
- 'blocktagstabtitle' => __( 'Blacklist tags', 'duracelltomi-google-tag-manager' ),
1172
- 'blocktriggerstabtitle' => __( 'Blacklist triggers', 'duracelltomi-google-tag-manager' ),
1173
- 'blockmacrostabtitle' => __( 'Blacklist variables', 'duracelltomi-google-tag-manager' ),
1174
- 'wpcf7tabtitle' => __( 'Contact Form 7', 'duracelltomi-google-tag-manager' ),
1175
- 'wctabtitle' => __( 'WooCommerce', 'duracelltomi-google-tag-manager' ),
1176
- 'gotabtitle' => __( 'Google Optimize', 'duracelltomi-google-tag-manager' ),
1177
- 'amptabtitle' => __( 'Accelerated Mobile Pages', 'duracelltomi-google-tag-manager' ),
1178
- 'cookiebottabtitle' => __( 'Cookiebot', 'duracelltomi-google-tag-manager' ),
1179
- 'weathertabtitle' => __( 'Weather & geo data', 'duracelltomi-google-tag-manager' ),
1180
- 'generaleventstabtitle' => __( 'General events', 'duracelltomi-google-tag-manager' ),
1181
- 'mediaeventstabtitle' => __( 'Media events', 'duracelltomi-google-tag-manager' ),
1182
- 'depecratedeventstabtitle' => __( 'Deprecated', 'duracelltomi-google-tag-manager' ),
1183
- 'sitetabtitle' => __( 'Site', 'duracelltomi-google-tag-manager' ),
1184
- 'misctabtitle' => __( 'Misc', 'duracelltomi-google-tag-manager' ),
1185
- );
1186
- wp_localize_script( 'admin-subtabs', 'gtm4wp', $subtabtexts );
1187
-
1188
- wp_enqueue_script( 'admin-subtabs' );
1189
- wp_enqueue_script( 'admin-tabcreator', $gtp4wp_plugin_url . 'js/admin-tabcreator.js', array( 'jquery-core' ), GTM4WP_VERSION );
1190
-
1191
- wp_enqueue_style( 'gtm4wp-validate', $gtp4wp_plugin_url . 'css/admin-gtm4wp.css', array(), GTM4WP_VERSION );
1192
- }
1193
- }
1194
-
1195
- function gtm4wp_admin_head() {
1196
- echo '
1197
- <style type="text/css">
1198
- .gtmid_validation_error,
1199
- .goid_validation_error,
1200
- .goid_ga_validation_error,
1201
- .ampid_validation_error,
1202
- .datalayername_validation_error,
1203
- .gtmauth_validation_error,
1204
- .gtmpreview_validation_error,
1205
- .gtm_wpconfig_set {
1206
- color: #c00;
1207
- font-weight: bold;
1208
- }
1209
- .gtmid_validation_error,
1210
- .goid_validation_error,
1211
- .goid_ga_validation_error,
1212
- .ampid_validation_error,
1213
- .datalayername_validation_error,
1214
- .gtmauth_validation_error,
1215
- .gtmpreview_validation_error {
1216
- display: none;
1217
- }
1218
- </style>
1219
- <script type="text/javascript">
1220
- jQuery(function() {
1221
- jQuery( "#gtm4wp-options\\\\[gtm-code\\\\]" )
1222
- .bind( "blur", function() {
1223
- var gtmid_regex = /^GTM-[A-Z0-9]+$/;
1224
- var gtmid_list = jQuery( this ).val().trim().split( "," );
1225
-
1226
- var gtmid_haserror = false;
1227
- for( var i=0; i<gtmid_list.length; i++ ) {
1228
- gtmid_haserror = gtmid_haserror || !gtmid_regex.test( gtmid_list[ i ] );
1229
- }
1230
-
1231
- if ( gtmid_haserror ) {
1232
- jQuery( ".gtmid_validation_error" )
1233
- .show();
1234
- } else {
1235
- jQuery( ".gtmid_validation_error" )
1236
- .hide();
1237
- }
1238
- });
1239
-
1240
- jQuery( "#gtm4wp-options\\\\[integrate-google-optimize-idlist\\\\]" )
1241
- .bind( "blur", function() {
1242
- var goid_regex = /^(GTM|OPT)-[A-Z0-9]+$/;
1243
- var goid_val = jQuery( this ).val().trim();
1244
- if ( "" == goid_val ) {
1245
- goid_list = [];
1246
- } else {
1247
- var goid_list = goid_val.split( "," );
1248
- }
1249
-
1250
- var goid_haserror = false;
1251
- for( var i=0; i<goid_list.length; i++ ) {
1252
- goid_haserror = goid_haserror || !goid_regex.test( goid_list[ i ] );
1253
- }
1254
-
1255
- if ( goid_haserror && (goid_list.length > 0) ) {
1256
- jQuery( ".goid_validation_error" )
1257
- .show();
1258
- } else {
1259
- jQuery( ".goid_validation_error" )
1260
- .hide();
1261
- }
1262
- });
1263
-
1264
- jQuery( "#gtm4wp-options\\\\[integrate-google-optimize-gaid\\\\]" )
1265
- .bind( "blur", function() {
1266
- var gogaid_regex = /^UA-[0-9]+-[0-9]+$/;
1267
- var gogaid_val = jQuery( this ).val().trim();
1268
- if ( "" == gogaid_val ) {
1269
- gogaid_list = [];
1270
- } else {
1271
- var gogaid_list = gogaid_val.split( "," );
1272
- }
1273
-
1274
- var gogaid_haserror = false;
1275
- for( var i=0; i<gogaid_list.length; i++ ) {
1276
- gogaid_haserror = gogaid_haserror || !gogaid_regex.test( gogaid_list[ i ] );
1277
- }
1278
-
1279
- if ( gogaid_haserror && (gogaid_list.length > 0) ) {
1280
- jQuery( ".goid_ga_validation_error" )
1281
- .show();
1282
- } else {
1283
- jQuery( ".goid_ga_validation_error" )
1284
- .hide();
1285
- }
1286
- });
1287
-
1288
- jQuery( "#gtm4wp-options\\\\[integrate-amp-gtm\\\\]" )
1289
- .bind( "blur", function() {
1290
- var ampid_regex = /^GTM-[A-Z0-9]+$/;
1291
- var ampid_val = jQuery( this ).val().trim();
1292
- if ( "" == ampid_val ) {
1293
- ampid_list = [];
1294
- } else {
1295
- var ampid_list = ampid_val.split( "," );
1296
- }
1297
-
1298
- var ampid_haserror = false;
1299
- for( var i=0; i<ampid_list.length; i++ ) {
1300
- ampid_haserror = ampid_haserror || !ampid_regex.test( gogaid_list[ i ] );
1301
- }
1302
-
1303
- if ( ampid_haserror && (ampid_list.length > 0) ) {
1304
- jQuery( ".ampid_validation_error" )
1305
- .show();
1306
- } else {
1307
- jQuery( ".ampid_validation_error" )
1308
- .hide();
1309
- }
1310
- });
1311
-
1312
- jQuery( "#gtm4wp-options\\\\[gtm-datalayer-variable-name\\\\]" )
1313
- .bind( "blur", function() {
1314
- var currentval = jQuery( this ).val();
1315
-
1316
- jQuery( ".datalayername_validation_error" )
1317
- .hide();
1318
-
1319
- if ( currentval != "" ) {
1320
- // I know this is not the exact definition for a variable name but I think other kind of variable names should not be used.
1321
- var gtmvarname_regex = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
1322
- if ( ! gtmvarname_regex.test( currentval ) ) {
1323
- jQuery( ".datalayername_validation_error" )
1324
- .show();
1325
- }
1326
- }
1327
- });
1328
-
1329
- jQuery( "#gtm4wp-options\\\\[gtm-env-gtm-auth\\\\]" )
1330
- .bind( "blur", function() {
1331
- var currentval = jQuery( this ).val();
1332
-
1333
- jQuery( ".gtmauth_validation_error" )
1334
- .hide();
1335
-
1336
- if ( currentval != "" ) {
1337
- var gtmauth_regex = /^[a-zA-Z0-9-_]+$/;
1338
- if ( ! gtmauth_regex.test( currentval ) ) {
1339
- jQuery( ".gtmauth_validation_error" )
1340
- .show();
1341
- }
1342
- }
1343
- });
1344
-
1345
- jQuery( "#gtm4wp-options\\\\[gtm-env-gtm-preview\\\\]" )
1346
- .bind( "blur", function() {
1347
- var currentval = jQuery( this ).val();
1348
-
1349
- jQuery( ".gtmpreview_validation_error" )
1350
- .hide();
1351
-
1352
- if ( currentval != "" ) {
1353
- var gtmpreview_regex = /^env-[0-9]+$/;
1354
- if ( ! gtmpreview_regex.test( currentval ) ) {
1355
- jQuery( ".gtmpreview_validation_error" )
1356
- .show();
1357
- }
1358
- }
1359
- });
1360
-
1361
- jQuery( document )
1362
- .on( "click", ".gtm4wp-notice .notice-dismiss", function( e ) {
1363
- jQuery.post(ajaxurl, {
1364
- action: "gtm4wp_dismiss_notice",
1365
- noticeid: jQuery( this ).closest(".gtm4wp-notice")
1366
- .attr( "data-href" )
1367
- .substring( 1 )
1368
- });
1369
- });
1370
- });
1371
- </script>';
1372
- }
1373
-
1374
- function gtm4wp_show_warning() {
1375
- global $gtm4wp_options, $gtp4wp_plugin_url, $gtm4wp_integratefieldtexts, $current_user,
1376
- $gtm4wp_def_user_notices_dismisses;
1377
-
1378
- $woo_plugin_active = is_plugin_active( $gtm4wp_integratefieldtexts[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ]['plugintocheck'] );
1379
- if ( $woo_plugin_active && function_exists( 'WC' ) ) {
1380
- $woo = WC();
1381
- } else {
1382
- $woo = null;
1383
- }
1384
-
1385
- $gtm4wp_user_notices_dismisses = get_user_meta( $current_user->ID, GTM4WP_USER_NOTICES_KEY, true );
1386
- if ( $gtm4wp_user_notices_dismisses === '' ) {
1387
- if ( is_array( $gtm4wp_def_user_notices_dismisses ) ) {
1388
- $gtm4wp_user_notices_dismisses = $gtm4wp_def_user_notices_dismisses;
1389
- } else {
1390
- $gtm4wp_user_notices_dismisses = array();
1391
- }
1392
- } else {
1393
- $gtm4wp_user_notices_dismisses = @unserialize( $gtm4wp_user_notices_dismisses );
1394
- if ( false === $gtm4wp_user_notices_dismisses || !is_array( $gtm4wp_user_notices_dismisses ) ) {
1395
- $gtm4wp_user_notices_dismisses = array();
1396
- }
1397
- }
1398
- $gtm4wp_user_notices_dismisses = array_merge( $gtm4wp_def_user_notices_dismisses, $gtm4wp_user_notices_dismisses );
1399
-
1400
- if ( ( trim( $gtm4wp_options[ GTM4WP_OPTION_GTM_CODE ] ) == '' ) && ( false === $gtm4wp_user_notices_dismisses['enter-gtm-code'] ) ) {
1401
- echo '<div class="gtm4wp-notice notice notice-error is-dismissible" data-href="?enter-gtm-code"><p><strong>' . sprintf( __( 'To start using Google Tag Manager for WordPress, please <a href="%s">enter your GTM ID</a>', 'duracelltomi-google-tag-manager' ), 'options-general.php?page=' . GTM4WP_ADMINSLUG ) . '</strong></p></div>';
1402
- }
1403
-
1404
- if ( (
1405
- ( '' != $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_AUTH ] ) && ( '' == $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_PREVIEW ] )
1406
- ) || (
1407
- ( '' == $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_AUTH ] ) && ( '' != $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_PREVIEW ] )
1408
- ) ) {
1409
- echo '<div class="gtm4wp-notice notice notice-error" data-href="?incomplete-gtm-env-config"><p><strong>' . sprintf( __( 'Incomplete Google Tag Manager environment configuration: either gtm_preview or gtm_auth parameter value is missing!', 'duracelltomi-google-tag-manager' ), 'options-general.php?page=' . GTM4WP_ADMINSLUG ) . '</strong></p></div>';
1410
- }
1411
-
1412
- if ( ( false === $gtm4wp_user_notices_dismisses['wc-ga-plugin-warning'] ) || ( false === $gtm4wp_user_notices_dismisses['wc-gayoast-plugin-warning'] ) ) {
1413
- $is_wc_active = $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKCLASSICEC ] ||
1414
- $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ||
1415
- $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ];
1416
-
1417
- if ( ( false === $gtm4wp_user_notices_dismisses['wc-ga-plugin-warning'] ) && $is_wc_active && is_plugin_active( 'woocommerce-google-analytics-integration/woocommerce-google-analytics-integration.php' ) ) {
1418
- echo '<div class="gtm4wp-notice notice notice-warning is-dismissible" data-href="?wc-ga-plugin-warning"><p><strong>' . __( 'Notice: you should deactivate the plugin "WooCommerce Google Analytics Integration" if you are using Google Analytics tags inside Google Tag Manager!', 'duracelltomi-google-tag-manager' ) . '</strong></p></div>';
1419
- }
1420
-
1421
- if ( ( false === $gtm4wp_user_notices_dismisses['wc-gayoast-plugin-warning'] ) && $is_wc_active && is_plugin_active( 'google-analytics-for-wordpress/googleanalytics.php' ) ) {
1422
- echo '<div class="gtm4wp-notice notice notice-warning is-dismissible" data-href="?wc-gayoast-plugin-warning"><p><strong>' . __( 'Notice: you should deactivate the plugin "Google Analytics for WordPress by MonsterInsights" if you are using Google Analytics tags inside Google Tag Manager!', 'duracelltomi-google-tag-manager' ) . '</strong></p></div>';
1423
- }
1424
- }
1425
-
1426
- if ( ( false === $gtm4wp_user_notices_dismisses['php72-warning'] ) && ( version_compare( PHP_VERSION, '7.2.0' ) < 0 ) ) {
1427
- echo '<div class="gtm4wp-notice notice notice-warning is-dismissible" data-href="?php72-warning"><p><strong>' . __( 'Warning: You are using an outdated version of PHP (v' . PHP_VERSION . ') that might be not compatible with future versions of the plugin Google Tag Manager for WordPress (GTM4WP). Please consider to upgrade your PHP.', 'duracelltomi-google-tag-manager' ) . '</strong></p></div>';
1428
- }
1429
- }
1430
-
1431
- function gtm4wp_dismiss_notice() {
1432
- global $gtm4wp_def_user_notices_dismisses, $current_user;
1433
-
1434
- $gtm4wp_user_notices_dismisses = get_user_meta( $current_user->ID, GTM4WP_USER_NOTICES_KEY, true );
1435
- if ( $gtm4wp_user_notices_dismisses === '' ) {
1436
- if ( is_array( $gtm4wp_def_user_notices_dismisses ) ) {
1437
- $gtm4wp_user_notices_dismisses = $gtm4wp_def_user_notices_dismisses;
1438
- } else {
1439
- $gtm4wp_user_notices_dismisses = array();
1440
- }
1441
- } else {
1442
- $gtm4wp_user_notices_dismisses = @unserialize( $gtm4wp_user_notices_dismisses );
1443
- if ( false === $gtm4wp_user_notices_dismisses || !is_array( $gtm4wp_user_notices_dismisses ) ) {
1444
- $gtm4wp_user_notices_dismisses = array();
1445
- }
1446
- }
1447
- $gtm4wp_user_notices_dismisses = array_merge( $gtm4wp_def_user_notices_dismisses, $gtm4wp_user_notices_dismisses );
1448
-
1449
- $noticeid = trim( basename( $_POST['noticeid'] ) );
1450
- if ( array_key_exists( $noticeid, $gtm4wp_user_notices_dismisses ) ) {
1451
- $gtm4wp_user_notices_dismisses[ $noticeid ] = true;
1452
- update_user_meta( $current_user->ID, GTM4WP_USER_NOTICES_KEY, serialize( $gtm4wp_user_notices_dismisses ) );
1453
- }
1454
- }
1455
-
1456
- function gtm4wp_add_plugin_action_links( $links, $file ) {
1457
- global $gtp4wp_plugin_basename;
1458
-
1459
- if ( $file != $gtp4wp_plugin_basename ) {
1460
- return $links;
1461
- }
1462
-
1463
- $settings_link = '<a href="' . menu_page_url( GTM4WP_ADMINSLUG, false ) . '">' . esc_html( __( 'Settings' ) ) . '</a>';
1464
-
1465
- array_unshift( $links, $settings_link );
1466
-
1467
- return $links;
1468
- }
1469
-
1470
- function gtm4wp_show_upgrade_notification( $current_plugin_metadata, $new_plugin_metadata ) {
1471
- if ( isset( $new_plugin_metadata->upgrade_notice ) && strlen( trim( $new_plugin_metadata->upgrade_notice ) ) > 0 ) {
1472
- echo '<p style="background-color: #d54e21; padding: 10px; color: #f9f9f9; margin-top: 10px"><strong>Important Upgrade Notice:</strong> ';
1473
- echo esc_html( $new_plugin_metadata->upgrade_notice ), '</p>';
1474
- }
1475
- }
1476
-
1477
- add_action( 'admin_init', 'gtm4wp_admin_init' );
1478
- add_action( 'admin_menu', 'gtm4wp_add_admin_page' );
1479
- add_action( 'admin_enqueue_scripts', 'gtm4wp_add_admin_js' );
1480
- add_action( 'admin_notices', 'gtm4wp_show_warning' );
1481
- add_action( 'admin_head', 'gtm4wp_admin_head' );
1482
- add_filter( 'plugin_action_links', 'gtm4wp_add_plugin_action_links', 10, 2 );
1483
- add_action( 'wp_ajax_gtm4wp_dismiss_notice', 'gtm4wp_dismiss_notice' );
1484
- add_action( 'in_plugin_update_message-duracelltomi-google-tag-manager-for-wordpress/duracelltomi-google-tag-manager-for-wordpress.php', 'gtm4wp_show_upgrade_notification', 10, 2 );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ define( 'GTM4WP_ADMINSLUG', 'gtm4wp-settings' );
3
+ define( 'GTM4WP_ADMIN_GROUP', 'gtm4wp-admin-group' );
4
+
5
+ define( 'GTM4WP_ADMIN_GROUP_GENERAL', 'gtm4wp-admin-group-general' );
6
+ define( 'GTM4WP_ADMIN_GROUP_GTMID', 'gtm4wp-admin-group-gtm-id' );
7
+ define( 'GTM4WP_ADMIN_GROUP_PLACEMENT', 'gtm4wp-admin-code-placement' );
8
+ define( 'GTM4WP_ADMIN_GROUP_INFO', 'gtm4wp-admin-group-datalayer-info' );
9
+
10
+ define( 'GTM4WP_ADMIN_GROUP_INCLUDES', 'gtm4wp-admin-group-includes' );
11
+ define( 'GTM4WP_ADMIN_GROUP_EVENTS', 'gtm4wp-admin-group-events' );
12
+ define( 'GTM4WP_ADMIN_GROUP_SCROLLER', 'gtm4wp-admin-group-scroller' );
13
+ define( 'GTM4WP_ADMIN_GROUP_BLACKLIST', 'gtm4wp-admin-group-blacklist-tags' );
14
+ define( 'GTM4WP_ADMIN_GROUP_INTEGRATION', 'gtm4wp-admin-group-integration' );
15
+ define( 'GTM4WP_ADMIN_GROUP_ADVANCED', 'gtm4wp-admin-group-advanced' );
16
+ define( 'GTM4WP_ADMIN_GROUP_CREDITS', 'gtm4wp-admin-group-credits' );
17
+
18
+ define( 'GTM4WP_USER_NOTICES_KEY', 'gtm4wp_user_notices_dismisses' );
19
+
20
+ define( 'GTM4WP_PHASE_STABLE', 'gtm4wp-phase-stable' );
21
+ define( 'GTM4WP_PHASE_BETA', 'gtm4wp-phase-beta' );
22
+ define( 'GTM4WP_PHASE_EXPERIMENTAL', 'gtm4wp-phase-experimental' );
23
+ define( 'GTM4WP_PHASE_DEPRECATED', 'gtm4wp-phase-deprecated' );
24
+
25
+ $GLOBALS['gtm4wp_def_user_notices_dismisses'] = array(
26
+ 'enter-gtm-code' => false,
27
+ 'wc-ga-plugin-warning' => false,
28
+ 'wc-gayoast-plugin-warning' => false,
29
+ 'php72-warning' => false,
30
+ 'deprecated-warning' => false,
31
+ );
32
+
33
+ $GLOBALS['gtm4wp_includefieldtexts'] = array(
34
+ GTM4WP_OPTION_INCLUDE_POSTTYPE => array(
35
+ 'label' => __( 'Posttype of current post/archive', 'duracelltomi-google-tag-manager' ),
36
+ 'description' => __( 'Check this option to include the type of the current post or archive page (post, page or any custom post type).', 'duracelltomi-google-tag-manager' ),
37
+ 'phase' => GTM4WP_PHASE_STABLE,
38
+ ),
39
+ GTM4WP_OPTION_INCLUDE_CATEGORIES => array(
40
+ 'label' => __( 'Category list of current post/archive', 'duracelltomi-google-tag-manager' ),
41
+ 'description' => __( 'Check this option to include the category names of the current post or archive page', 'duracelltomi-google-tag-manager' ),
42
+ 'phase' => GTM4WP_PHASE_STABLE,
43
+ ),
44
+ GTM4WP_OPTION_INCLUDE_TAGS => array(
45
+ 'label' => __( 'Tags of current post', 'duracelltomi-google-tag-manager' ),
46
+ 'description' => __( 'Check this option to include the tags of the current post.', 'duracelltomi-google-tag-manager' ),
47
+ 'phase' => GTM4WP_PHASE_STABLE,
48
+ ),
49
+ GTM4WP_OPTION_INCLUDE_AUTHORID => array(
50
+ 'label' => __( 'Post author ID', 'duracelltomi-google-tag-manager' ),
51
+ 'description' => __( 'Check this option to include the ID of the author on the current post or author page.', 'duracelltomi-google-tag-manager' ),
52
+ 'phase' => GTM4WP_PHASE_STABLE,
53
+ ),
54
+ GTM4WP_OPTION_INCLUDE_AUTHOR => array(
55
+ 'label' => __( 'Post author name', 'duracelltomi-google-tag-manager' ),
56
+ 'description' => __( 'Check this option to include the name of the author on the current post or author page.', 'duracelltomi-google-tag-manager' ),
57
+ 'phase' => GTM4WP_PHASE_STABLE,
58
+ ),
59
+ GTM4WP_OPTION_INCLUDE_POSTDATE => array(
60
+ 'label' => __( 'Post date', 'duracelltomi-google-tag-manager' ),
61
+ 'description' => __( 'Check this option to include the date of the current post. This will include 4 dataLayer variables: full date, post year, post month, post date.', 'duracelltomi-google-tag-manager' ),
62
+ 'phase' => GTM4WP_PHASE_STABLE,
63
+ ),
64
+ GTM4WP_OPTION_INCLUDE_POSTTITLE => array(
65
+ 'label' => __( 'Post title', 'duracelltomi-google-tag-manager' ),
66
+ 'description' => __( 'Check this option to include the title of the current post.', 'duracelltomi-google-tag-manager' ),
67
+ 'phase' => GTM4WP_PHASE_STABLE,
68
+ ),
69
+ GTM4WP_OPTION_INCLUDE_POSTCOUNT => array(
70
+ 'label' => __( 'Post count', 'duracelltomi-google-tag-manager' ),
71
+ 'description' => __( 'Check this option to include the count of the posts currently shown on the page and the total number of posts in the category/tag/any taxonomy.', 'duracelltomi-google-tag-manager' ),
72
+ 'phase' => GTM4WP_PHASE_STABLE,
73
+ ),
74
+ GTM4WP_OPTION_INCLUDE_POSTID => array(
75
+ 'label' => __( 'Post ID', 'duracelltomi-google-tag-manager' ),
76
+ 'description' => __( 'Check this option to include the post id.', 'duracelltomi-google-tag-manager' ),
77
+ 'phase' => GTM4WP_PHASE_STABLE,
78
+ ),
79
+ GTM4WP_OPTION_INCLUDE_POSTFORMAT => array(
80
+ 'label' => __( 'Post Format', 'duracelltomi-google-tag-manager' ),
81
+ 'description' => __( 'Check this option to include the post format.', 'duracelltomi-google-tag-manager' ),
82
+ 'phase' => GTM4WP_PHASE_STABLE,
83
+ ),
84
+ GTM4WP_OPTION_INCLUDE_POSTTERMLIST => array(
85
+ "label" => __( "Post Terms", 'duracelltomi-google-tag-manager' ),
86
+ "description" => __( "Check this option to include taxonomy values associated with a given post.", 'duracelltomi-google-tag-manager' ),
87
+ "phase" => GTM4WP_PHASE_STABLE
88
+ ),
89
+ GTM4WP_OPTION_INCLUDE_SEARCHDATA => array(
90
+ 'label' => __( 'Search data', 'duracelltomi-google-tag-manager' ),
91
+ 'description' => __( 'Check this option to include the search term, referring page URL and number of results on the search page.', 'duracelltomi-google-tag-manager' ),
92
+ 'phase' => GTM4WP_PHASE_STABLE,
93
+ ),
94
+ GTM4WP_OPTION_INCLUDE_LOGGEDIN => array(
95
+ 'label' => __( 'Logged in status', 'duracelltomi-google-tag-manager' ),
96
+ 'description' => __( 'Check this option to include whether there is a logged in user on your website.', 'duracelltomi-google-tag-manager' ),
97
+ 'phase' => GTM4WP_PHASE_STABLE,
98
+ ),
99
+ GTM4WP_OPTION_INCLUDE_USERROLE => array(
100
+ 'label' => __( 'Logged in user role', 'duracelltomi-google-tag-manager' ),
101
+ 'description' => __( 'Check this option to include the role of the logged in user.', 'duracelltomi-google-tag-manager' ),
102
+ 'phase' => GTM4WP_PHASE_STABLE,
103
+ ),
104
+ GTM4WP_OPTION_INCLUDE_USERID => array(
105
+ 'label' => __( 'Logged in user ID', 'duracelltomi-google-tag-manager' ),
106
+ 'description' => __( 'Check this option to include the ID of the logged in user.', 'duracelltomi-google-tag-manager' ),
107
+ 'phase' => GTM4WP_PHASE_STABLE,
108
+ ),
109
+ GTM4WP_OPTION_INCLUDE_USERNAME => array(
110
+ 'label' => __( 'Logged in user name', 'duracelltomi-google-tag-manager' ),
111
+ 'description' => __( 'Check this option to include the username of the logged in user.', 'duracelltomi-google-tag-manager' ),
112
+ 'phase' => GTM4WP_PHASE_STABLE,
113
+ ),
114
+ GTM4WP_OPTION_INCLUDE_USEREMAIL => array(
115
+ 'label' => __( 'Logged in user email', 'duracelltomi-google-tag-manager' ),
116
+ 'description' => __( 'Check this option to include the email address of the logged in user.', 'duracelltomi-google-tag-manager' ),
117
+ 'phase' => GTM4WP_PHASE_STABLE,
118
+ ),
119
+ GTM4WP_OPTION_INCLUDE_USERREGDATE => array(
120
+ 'label' => __( 'Logged in user creation date', 'duracelltomi-google-tag-manager' ),
121
+ 'description' => __( 'Check this option to include the date of creation (registration) of the logged in user.', 'duracelltomi-google-tag-manager' ),
122
+ 'phase' => GTM4WP_PHASE_STABLE,
123
+ ),
124
+ GTM4WP_OPTION_INCLUDE_VISITOR_IP => array(
125
+ 'label' => __( 'Visitor IP', 'duracelltomi-google-tag-manager' ),
126
+ 'description' => __( 'Check this option to include the IP address of the visitor. You might use this to filter internal traffic inside your GTM container. Please be aware that per GDPR its not allowed to transmit this full IP address to Google Analytics or to any other measurement system without explicit consent from the visitor.', 'duracelltomi-google-tag-manager' ),
127
+ 'phase' => GTM4WP_PHASE_STABLE,
128
+ ),
129
+ GTM4WP_OPTION_INCLUDE_REMARKETING => array(
130
+ 'label' => __( 'Remarketing variable', 'duracelltomi-google-tag-manager' ),
131
+ 'description' => __( 'Check this option to include a dataLayer variable where all dataLayer values are stored to be included in your Google Ads remarketing tag as a custom variable field', 'duracelltomi-google-tag-manager' ),
132
+ 'phase' => GTM4WP_PHASE_DEPRECATED,
133
+ ),
134
+ GTM4WP_OPTION_INCLUDE_BROWSERDATA => array(
135
+ 'label' => __( 'Browser data *', 'duracelltomi-google-tag-manager' ),
136
+ 'description' => __( 'Check this option to include the name, version and engine data of the browser the visitor uses.', 'duracelltomi-google-tag-manager' )
137
+ ),
138
+ GTM4WP_OPTION_INCLUDE_OSDATA => array(
139
+ 'label' => __( 'OS data *', 'duracelltomi-google-tag-manager' ),
140
+ 'description' => __( 'Check this option to include the name and version of the operating system the visitor uses.', 'duracelltomi-google-tag-manager' )
141
+ ),
142
+ GTM4WP_OPTION_INCLUDE_DEVICEDATA => array(
143
+ 'label' => __( 'Device data *', 'duracelltomi-google-tag-manager' ),
144
+ 'description' => __( 'Check this option to include the type of device the user is currently using (desktop, tablet or mobile) including manufacturer and model data.', 'duracelltomi-google-tag-manager' )
145
+ ),
146
+ GTM4WP_OPTION_INCLUDE_MISCGEO => array(
147
+ 'label' => __( 'Geo data', 'duracelltomi-google-tag-manager' ),
148
+ 'description' => __( 'Add geo data (latitude, longitude, country, city, etc) of the current visitor (provided by ipstack.com)', 'duracelltomi-google-tag-manager' ),
149
+ 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
150
+ ),
151
+ GTM4WP_OPTION_INCLUDE_MISCGEOAPI => array(
152
+ 'label' => __( 'IPStack.com API key', 'duracelltomi-google-tag-manager' ),
153
+ 'description' => sprintf( __( 'Enter your IPStack.com API key here. <a href="%s" target="_blank" rel="noopener">Get a free API key here</a>.', 'duracelltomi-google-tag-manager' ), 'https://ipstack.com/product?utm_source=gtm4wp&utm_medium=link&utm_campaign=gtm4wp-google-tag-manager-for-wordpress' ),
154
+ 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
155
+ ),
156
+ GTM4WP_OPTION_INCLUDE_MISCGEOCF => array(
157
+ 'label' => __( 'Cloudflare country code', 'duracelltomi-google-tag-manager' ),
158
+ 'description' => __( 'Add the country code of the user provided by Cloudflare (if Cloudflare is used with your site)', 'duracelltomi-google-tag-manager' ),
159
+ 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
160
+ ),
161
+ GTM4WP_OPTION_INCLUDE_WEATHER => array(
162
+ 'label' => __( 'Weather data', 'duracelltomi-google-tag-manager' ),
163
+ 'description' => sprintf(
164
+ __(
165
+ 'Check this option to include the current weather conditions around the current visitor.<br /><br />' .
166
+ '<strong>Attention!</strong> This feature uses <a href="%s" target="_blank" rel="noopener">ipstack.com</a> and ' .
167
+ '<a href="%s" target="_blank" rel="noopener">openweathermap.org</a> to collect data.<br />' .
168
+ "Depending on your website's traffic, additional fees may apply!<br />" .
169
+ 'This plugin caches weather data for 1 hour to lower the need to access those services.<br /><br />' .
170
+ 'If you activate weather data, <strong>you will need</strong> to add an IPStack.com API key regardless of whether you ' .
171
+ "activate the 'Geo data' option!",
172
+ 'duracelltomi-google-tag-manager'
173
+ ),
174
+ 'https://ipstack.com/product?utm_source=gtm4wp&utm_medium=link&utm_campaign=gtm4wp-google-tag-manager-for-wordpress',
175
+ 'http://openweathermap.org/price?utm_source=gtm4wp&utm_medium=link&utm_campaign=gtm4wp-google-tag-manager-for-wordpress'
176
+ ),
177
+ 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
178
+ ),
179
+ GTM4WP_OPTION_INCLUDE_WEATHERUNITS => array(
180
+ 'label' => __( 'Weather data units', 'duracelltomi-google-tag-manager' ),
181
+ 'description' => __( 'Select which temperature units you would like to use.', 'duracelltomi-google-tag-manager' ),
182
+ 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
183
+ ),
184
+ GTM4WP_OPTION_INCLUDE_WEATHEROWMAPI => array(
185
+ 'label' => __( 'OpenWeatherMap API key', 'duracelltomi-google-tag-manager' ),
186
+ 'description' => sprintf( __( 'Enter your OpenWeatherMap API key here. <a href="%s" target="_blank" rel="noopener">Get a free API key here</a>.', 'duracelltomi-google-tag-manager' ), 'http://openweathermap.org/price?utm_source=gtm4wp&utm_medium=link&utm_campaign=gtm4wp-google-tag-manager-for-wordpress' ),
187
+ 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
188
+ ),
189
+ GTM4WP_OPTION_INCLUDE_SITEID => array(
190
+ 'label' => __( 'Site ID', 'duracelltomi-google-tag-manager' ),
191
+ 'description' => __( 'ID of the current site in a WordPress Multisite environment', 'duracelltomi-google-tag-manager' ),
192
+ 'phase' => GTM4WP_PHASE_STABLE,
193
+ ),
194
+ GTM4WP_OPTION_INCLUDE_SITENAME => array(
195
+ 'label' => __( 'Site name', 'duracelltomi-google-tag-manager' ),
196
+ 'description' => __( 'Name of the current site in a WordPress Multisite environment', 'duracelltomi-google-tag-manager' ),
197
+ 'phase' => GTM4WP_PHASE_STABLE,
198
+ ),
199
+ );
200
+
201
+ $GLOBALS['gtm4wp_eventfieldtexts'] = array(
202
+ GTM4WP_OPTION_EVENTS_FORMMOVE => array(
203
+ 'label' => __( 'Form fill events (gtm4wp.formElementEnter & gtm4wp.formElementLeave)', 'duracelltomi-google-tag-manager' ),
204
+ 'description' => __( 'Check this option to include a Tag Manager event when a visitor moves between elements of a form (comment, contact, etc).', 'duracelltomi-google-tag-manager' ),
205
+ 'phase' => GTM4WP_PHASE_STABLE,
206
+ ),
207
+ GTM4WP_OPTION_EVENTS_NEWUSERREG => array(
208
+ 'label' => __( 'New user registration', 'duracelltomi-google-tag-manager' ),
209
+ 'description' => __( 'Check this option to include a Tag Manager event when a new user registration has been completed on the frontend of your site (admin events not included)', 'duracelltomi-google-tag-manager' ),
210
+ 'phase' => GTM4WP_PHASE_STABLE,
211
+ ),
212
+ GTM4WP_OPTION_EVENTS_USERLOGIN => array(
213
+ 'label' => __( 'User logged in', 'duracelltomi-google-tag-manager' ),
214
+ 'description' => __( 'Check this option to include a Tag Manager event when an existing user has been logged in on the frontend of your site (admin events not included)', 'duracelltomi-google-tag-manager' ),
215
+ 'phase' => GTM4WP_PHASE_STABLE,
216
+ ),
217
+ GTM4WP_OPTION_EVENTS_YOUTUBE => array(
218
+ 'label' => __( 'YouTube video events', 'duracelltomi-google-tag-manager' ),
219
+ 'description' => __( 'Check this option to include a Tag Manager event when a visitor interacts with a YouTube video embeded on your site.', 'duracelltomi-google-tag-manager' ),
220
+ 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
221
+ ),
222
+ GTM4WP_OPTION_EVENTS_VIMEO => array(
223
+ 'label' => __( 'Vimeo video events', 'duracelltomi-google-tag-manager' ),
224
+ 'description' => __( 'Check this option to include a Tag Manager event when a visitor interacts with a Vimeo video embeded on your site.', 'duracelltomi-google-tag-manager' ),
225
+ 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
226
+ ),
227
+ GTM4WP_OPTION_EVENTS_SOUNDCLOUD => array(
228
+ 'label' => __( 'Soundcloud events', 'duracelltomi-google-tag-manager' ),
229
+ 'description' => __( 'Check this option to include a Tag Manager event when a visitor interacts with a Soundcloud media embeded on your site.', 'duracelltomi-google-tag-manager' ),
230
+ 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
231
+ )
232
+ );
233
+
234
+ $GLOBALS['gtm4wp_scrollerfieldtexts'] = array(
235
+ GTM4WP_OPTION_SCROLLER_ENABLED => array(
236
+ 'label' => __( 'Enabled', 'duracelltomi-google-tag-manager' ),
237
+ 'description' => __( 'Enable scroll tracker script on your website.', 'duracelltomi-google-tag-manager' ),
238
+ 'phase' => GTM4WP_PHASE_STABLE,
239
+ ),
240
+ GTM4WP_OPTION_SCROLLER_DEBUGMODE => array(
241
+ 'label' => __( 'Debug mode', 'duracelltomi-google-tag-manager' ),
242
+ 'description' => __( 'Fire console.log() commands instead of dataLayer events.', 'duracelltomi-google-tag-manager' ),
243
+ 'phase' => GTM4WP_PHASE_STABLE,
244
+ ),
245
+ GTM4WP_OPTION_SCROLLER_CALLBACKTIME => array(
246
+ 'label' => __( 'Time delay before location check', 'duracelltomi-google-tag-manager' ),
247
+ 'description' => __( 'Enter the number of milliseconds after the script checks the current location. It prevents too many events being fired while scrolling.', 'duracelltomi-google-tag-manager' ),
248
+ 'phase' => GTM4WP_PHASE_STABLE,
249
+ ),
250
+ GTM4WP_OPTION_SCROLLER_DISTANCE => array(
251
+ 'label' => __( 'Minimum distance', 'duracelltomi-google-tag-manager' ),
252
+ 'description' => __( 'The minimum amount of pixels that a visitor has to scroll before we treat the move as scrolling.', 'duracelltomi-google-tag-manager' ),
253
+ 'phase' => GTM4WP_PHASE_STABLE,
254
+ ),
255
+ GTM4WP_OPTION_SCROLLER_CONTENTID => array(
256
+ 'label' => __( 'Content ID', 'duracelltomi-google-tag-manager' ),
257
+ 'description' => __( 'Enter the DOM ID of the content element in your template. Leave it empty for default(content). Do not include the # sign.', 'duracelltomi-google-tag-manager' ),
258
+ 'phase' => GTM4WP_PHASE_STABLE,
259
+ ),
260
+ GTM4WP_OPTION_SCROLLER_READERTIME => array(
261
+ 'label' => __( 'Scroller time', 'duracelltomi-google-tag-manager' ),
262
+ 'description' => __( 'Enter the number of seconds after the the scroller user is being treated as a reader, someone who really reads the content, not just scrolls through it.', 'duracelltomi-google-tag-manager' ),
263
+ 'phase' => GTM4WP_PHASE_STABLE,
264
+ ),
265
+ );
266
+
267
+ $GLOBALS['gtm4wp_integratefieldtexts'] = array(
268
+ GTM4WP_OPTION_INTEGRATE_WPCF7 => array(
269
+ 'label' => __( 'Contact Form 7', 'duracelltomi-google-tag-manager' ),
270
+ 'description' => __( 'Check this to include a dataLayer event after a successfull form submission.', 'duracelltomi-google-tag-manager' ),
271
+ 'phase' => GTM4WP_PHASE_STABLE,
272
+ 'plugintocheck' => 'contact-form-7/wp-contact-form-7.php',
273
+ ),
274
+ GTM4WP_OPTION_INTEGRATE_WCTRACKCLASSICEC => array(
275
+ 'label' => __( 'Track classic e-commerce', 'duracelltomi-google-tag-manager' ),
276
+ 'description' => __( 'This feature is deprecated and will be removed soon! You should upgrade to enhanced ecommerce as soon as possible.', 'duracelltomi-google-tag-manager' ),
277
+ 'phase' => GTM4WP_PHASE_DEPRECATED
278
+ ),
279
+ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC => array(
280
+ 'label' => __( 'Track enhanced e-commerce', 'duracelltomi-google-tag-manager' ),
281
+ 'description' => sprintf(
282
+ __(
283
+ 'Choose this option if you would like to track e-commerce data using '.
284
+ '<a href="%s" target="_blank" rel="noopener">enhanced ecommerce tracking</a>.<br>'.
285
+ 'Use the plugin\'s official guides to setup your Google Tag Manager container:<br>'.
286
+ '<ul><li><a href="%s" target="_blank" rel="noopener">Google Analytics 3 / Universal Analytics setup</a></li>'.
287
+ '<li><a href="%s" target="_blank" rel="noopener">Google Analytics 4 setup</a></li></ul>'
288
+ , 'duracelltomi-google-tag-manager' )
289
+ , 'https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce'
290
+ , 'https://gtm4wp.com/how-to-articles/how-to-setup-enhanced-ecommerce-tracking'
291
+ , 'https://gtm4wp.com/how-to-articles/how-to-setup-enhanced-ecommerce-tracking-google-analytics-4-ga4-version' ),
292
+ 'phase' => GTM4WP_PHASE_STABLE,
293
+ 'plugintocheck' => 'woocommerce/woocommerce.php',
294
+ ),
295
+ GTM4WP_OPTION_INTEGRATE_WCPRODPERIMPRESSION => array(
296
+ 'label' => __( 'Products per impression', 'duracelltomi-google-tag-manager' ),
297
+ 'description' => __(
298
+ 'If you have many products shown on product category pages and/or on your site home, you could miss pageviews in Google Analytics due to the ' .
299
+ 'amount of data that is needed to be sent. To prevent this, you can split product impression data into multiple Google Analytics events by ' .
300
+ 'entering a number here (minimum 10-15 recommended) and adding gtm4wp.productImpressionEEC into your Google Analytics ecommerce event helper ' .
301
+ "tag's trigger.<br /><br />Leave this value 0 to include product impression data in your pageview hit.",
302
+ 'duracelltomi-google-tag-manager'
303
+ ),
304
+ 'phase' => GTM4WP_PHASE_STABLE
305
+ ),
306
+ GTM4WP_OPTION_INTEGRATE_WCEECCARTASFIRSTSTEP => array(
307
+ 'label' => __( 'Cart as 1st checkout step', 'duracelltomi-google-tag-manager' ),
308
+ 'description' => __( 'Enable this to track the cart page as the first checkout step in enhanced ecommerce instead of the checkout page itself', 'duracelltomi-google-tag-manager' ),
309
+ 'phase' => GTM4WP_PHASE_STABLE
310
+ ),
311
+ GTM4WP_OPTION_INTEGRATE_WCEINCLUDECARTINDL => array(
312
+ "label" => __( "Cart content in data layer", 'duracelltomi-google-tag-manager' ),
313
+ "description" => __( "Enable this option to include the content of the cart in the data layer on each page. Needs WooCommerce v3.2 or newer. Especially useful for site personalization with Google Optimize.", 'duracelltomi-google-tag-manager' ),
314
+ "phase" => GTM4WP_PHASE_STABLE
315
+ ),
316
+ GTM4WP_OPTION_INTEGRATE_WCUSEFULLCATEGORYPATH => array(
317
+ 'label' => __( 'Include full category path.', 'duracelltomi-google-tag-manager' ),
318
+ 'description' => __( 'Check this to inclulde the full category path of each product in enhanced ecommerce tracking. WARNING! This can lead to performance issues on large sites with lots of traffic!', 'duracelltomi-google-tag-manager' ),
319
+ 'phase' => GTM4WP_PHASE_STABLE
320
+ ),
321
+ GTM4WP_OPTION_INTEGRATE_WCEECBRANDTAXONOMY => array(
322
+ "label" => __( "Taxonomy to be used for product brands", 'duracelltomi-google-tag-manager' ),
323
+ "description" => __( "Select which custom taxonomy is being used to add the brand of products", 'duracelltomi-google-tag-manager' ),
324
+ "phase" => GTM4WP_PHASE_STABLE
325
+ ),
326
+ GTM4WP_OPTION_INTEGRATE_WCCUSTOMERDATA => array(
327
+ 'label' => __( 'Customer data in data layer', 'duracelltomi-google-tag-manager' ),
328
+ 'description' => __( 'Enable this to add all customer data (billing and shipping data, total number of orders and order value) into the data layer (WooCommerce 3.x required)', 'duracelltomi-google-tag-manager' ),
329
+ 'phase' => GTM4WP_PHASE_STABLE
330
+ ),
331
+ GTM4WP_OPTION_INTEGRATE_WCORDERDATA => array(
332
+ 'label' => __( 'Order data in data layer', 'duracelltomi-google-tag-manager' ),
333
+ 'description' => __( 'Enable this to add all order attribute into the data layer on the order received page regardless and independently from classic and enhanced ecommerce tracking (WooCommerce 3.x required)', 'duracelltomi-google-tag-manager' ),
334
+ 'phase' => GTM4WP_PHASE_STABLE
335
+ ),
336
+ GTM4WP_OPTION_INTEGRATE_WCEXCLUDETAX => array(
337
+ 'label' => __( 'Exclude tax from revenue', 'duracelltomi-google-tag-manager' ),
338
+ 'description' => __( 'Enable this to exclude tax from the revenue variable while generating the purchase data', 'duracelltomi-google-tag-manager' ),
339
+ 'phase' => GTM4WP_PHASE_STABLE
340
+ ), GTM4WP_OPTION_INTEGRATE_WCORDERMAXAGE => array(
341
+ 'label' => __( 'Only track orders younger than', 'duracelltomi-google-tag-manager' ),
342
+ 'description' => __( 'To prevent duplicate transaction tracking at the order received page, enter the maximum age (in minutes) of the order or its payment for the transaction to be measured. Viewing the order received page of older orders will be ignored from transaction tracking, as it is considered to be a measured in an earlier session.', 'duracelltomi-google-tag-manager' ),
343
+ 'phase' => GTM4WP_PHASE_EXPERIMENTAL
344
+ ),
345
+ GTM4WP_OPTION_INTEGRATE_WCEXCLUDESHIPPING => array(
346
+ 'label' => __( 'Exclude shipping from revenue', 'duracelltomi-google-tag-manager' ),
347
+ 'description' => __( 'Enable this to exclude shipping costs from the revenue variable while generating the purchase data', 'duracelltomi-google-tag-manager' ),
348
+ 'phase' => GTM4WP_PHASE_STABLE
349
+ ),
350
+ GTM4WP_OPTION_INTEGRATE_WCREMARKETING => array(
351
+ 'label' => __( 'Google Ads Remarketing', 'duracelltomi-google-tag-manager' ),
352
+ 'description' => __( 'Enable this to add Google Ads dynamic remarketing variables to the dataLayer', 'duracelltomi-google-tag-manager' ),
353
+ 'phase' => GTM4WP_PHASE_DEPRECATED
354
+ ),
355
+ GTM4WP_OPTION_INTEGRATE_WCBUSINESSVERTICAL => array(
356
+ 'label' => __( 'Google Ads Business Vertical', 'duracelltomi-google-tag-manager' ),
357
+ 'description' => sprintf(
358
+ __(
359
+ 'Select which vertical category to add next to each product to utilize dynamic remarketing for Google Ads.'.
360
+ '<br>Use the plugin\'s <a href="%s" target="_blank" rel="noopener">official setup guide for dynamic remarketing</a> '.
361
+ 'to setup your Google Tag Manager container.'
362
+ , 'duracelltomi-google-tag-manager' )
363
+ , 'https://gtm4wp.com/how-to-articles/how-to-setup-dynamic-remarketing-in-google-ads-adwords'),
364
+ 'phase' => GTM4WP_PHASE_STABLE
365
+ ),
366
+ GTM4WP_OPTION_INTEGRATE_WCREMPRODIDPREFIX => array(
367
+ 'label' => __( 'Product ID prefix', 'duracelltomi-google-tag-manager' ),
368
+ 'description' => __( "Some product feed generator plugins prefix product IDs with a fixed text like 'woocommerce_gpf'. You can enter this prefix here so that tags in your website include this prefix as well.", 'duracelltomi-google-tag-manager' ),
369
+ 'phase' => GTM4WP_PHASE_STABLE
370
+ ),
371
+ GTM4WP_OPTION_INTEGRATE_WCUSESKU => array(
372
+ 'label' => __( 'Use SKU instead of ID', 'duracelltomi-google-tag-manager' ),
373
+ 'description' => __( 'Check this to use product SKU instead of the ID of the products for remarketing and ecommerce tracking. Will fallback to ID if no SKU is set.', 'duracelltomi-google-tag-manager' ),
374
+ 'phase' => GTM4WP_PHASE_STABLE
375
+ ),
376
+ GTM4WP_OPTION_INTEGRATE_WCNOORDERTRACKEDFLAG => array(
377
+ 'label' => __( 'Do not flag orders as being tracked', 'duracelltomi-google-tag-manager' ),
378
+ 'description' => __(
379
+ 'Check this to prevent the plugin to flag orders as being already tracked.<br /><br />This ensures that no order data will be tracked ' .
380
+ 'multiple times in any ad or measurement system so please only enable this feature if you really need it (with iDeal you might need this)!',
381
+ 'duracelltomi-google-tag-manager'
382
+ ),
383
+ 'phase' => GTM4WP_PHASE_STABLE
384
+ ),
385
+
386
+ GTM4WP_OPTION_INTEGRATE_GOOGLEOPTIMIZEIDS => array(
387
+ 'label' => __( 'Google Optimize container ID list', 'duracelltomi-google-tag-manager' ),
388
+ 'description' => sprintf(
389
+ __(
390
+ 'Enter a comma separated list of Google Optimize container IDs that you would like to use on your site.<br />' .
391
+ 'This plugin will add the <a href="%s">page-hiding snippet</a> to your pages.<br />',
392
+ 'duracelltomi-google-tag-manager'
393
+ ),
394
+ 'https://developers.google.com/optimize/#the_page-hiding_snippet_code'
395
+ ) .
396
+ '<br /><span class="goid_validation_error">' . __( 'This does not seems to be a valid Google Optimize ID! Valid format: GTM-XXXXXX or OPT-XXXXXX where X can be numbers and capital letters. Use comma without any space (,) to enter multpile IDs.', 'duracelltomi-google-tag-manager' ) . '</span>',
397
+ 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
398
+ ),
399
+ GTM4WP_OPTION_INTEGRATE_GOOGLEOPTIMIZETIMEOUT => array(
400
+ 'label' => __( 'Google Optimize page-hiding timeout', 'duracelltomi-google-tag-manager' ),
401
+ 'description' => __( 'Enter here the amount of time in milliseconds that the page-hiding snippet should wait before page content gets visible even if Google Optimize has not been completely loaded yet.', 'duracelltomi-google-tag-manager' ),
402
+ 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
403
+ ),
404
+
405
+ GTM4WP_OPTION_INTEGRATE_AMPID => array(
406
+ 'label' => __( "Google Tag Manager 'AMP' Container ID", 'duracelltomi-google-tag-manager' ),
407
+ 'description' => sprintf( __( 'Enter a comma separated list of Google Tag Manager container IDs that you would like to use on your site. This plugin will add the <a href="%s">AMP GTM snippet</a> to your AMP pages.', 'duracelltomi-google-tag-manager' ), 'https://support.google.com/tagmanager/answer/6103696?hl=en' ) .
408
+ '<br /><span class="ampid_validation_error">' . __( 'This does not seems to be a valid Google Tag Manager Container ID! Valid format: GTM-XXXXXX where X can be numbers and capital letters. Use comma without any space (,) to enter multpile IDs.', 'duracelltomi-google-tag-manager' ) . '</span>',
409
+ 'phase' => GTM4WP_PHASE_EXPERIMENTAL,
410
+ 'plugintocheck' => 'amp/amp.php',
411
+ ),
412
+
413
+ GTM4WP_OPTION_INTEGRATE_COOKIEBOT => array(
414
+ 'label' => __( 'Cookiebot auto blocking', 'duracelltomi-google-tag-manager' ),
415
+ 'description' => sprintf( __( 'Enable this checkbox if you wish to use the <a href="%s" target="_blank" rel="noopener">automatic cookie blocking mode of Cookiebot with Google Tag Manager</a>.', 'duracelltomi-google-tag-manager' ), 'https://support.cookiebot.com/hc/en-us/articles/360009192739-Google-Tag-Manager-and-Automatic-cookie-blocking' ),
416
+ 'phase' => GTM4WP_PHASE_STABLE
417
+ ),
418
+ );
419
+
420
+ $GLOBALS['gtm4wp_advancedfieldtexts'] = array(
421
+ GTM4WP_OPTION_DATALAYER_NAME => array(
422
+ 'label' => __( 'dataLayer variable name', 'duracelltomi-google-tag-manager' ),
423
+ 'description' => __( 'In some cases you need to rename the dataLayer variable. You can enter your name here. Leave black for default name: dataLayer', 'duracelltomi-google-tag-manager' ),
424
+ 'phase' => GTM4WP_PHASE_STABLE,
425
+ ),
426
+ GTM4WP_OPTION_ENV_GTM_AUTH => array(
427
+ 'label' => __( 'Environment gtm_auth parameter', 'duracelltomi-google-tag-manager' ),
428
+ 'description' => __( 'Enter the gtm_auth parameter of the Google Tag Manager environment that has to be activated on this site. Both gtm_auth and gtm_preview parameters are required to activate the desired environment.', 'duracelltomi-google-tag-manager' ),
429
+ 'phase' => GTM4WP_PHASE_STABLE,
430
+ ),
431
+ GTM4WP_OPTION_ENV_GTM_PREVIEW => array(
432
+ 'label' => __( 'Environment gtm_preview parameter', 'duracelltomi-google-tag-manager' ),
433
+ 'description' => __( 'Enter the gtm_auth parameter of the Google Tag Manager environment that has to be activated on this site. Both gtm_auth and gtm_preview parameters are required to activate the desired environment.', 'duracelltomi-google-tag-manager' ),
434
+ 'phase' => GTM4WP_PHASE_STABLE,
435
+ ),
436
+ GTM4WP_OPTION_DONOTTRACK => array(
437
+ 'label' => __( "Include browser 'Do not track' setting", 'duracelltomi-google-tag-manager' ),
438
+ 'description' => __( 'Add into the data layer whether the user has asked not to track any website interaction. You may want to respect this and disable all tags if this variable is set in the data layer.', 'duracelltomi-google-tag-manager' ),
439
+ 'phase' => GTM4WP_PHASE_STABLE,
440
+ ),
441
+ GTM4WP_OPTION_LOADEARLY => array(
442
+ 'label' => __( 'Load GTM container as early as possible', 'duracelltomi-google-tag-manager' ),
443
+ 'description' => __( "Turning on this option will load your Google Tag Manager container as early as possible during page load. This can cause issues if you are using jQuery in your custom HTML tags that fire on 'Page View' events.", 'duracelltomi-google-tag-manager' ),
444
+ 'phase' => GTM4WP_PHASE_STABLE,
445
+ ),
446
+ GTM4WP_OPTION_GTMDOMAIN => array(
447
+ 'label' => __( 'Container domain name', 'duracelltomi-google-tag-manager' ),
448
+ 'description' => __( "Enter your custom domain name if you are using a server side GTM container for tracking. Leave this blank to use www.googletagmanager.com", 'duracelltomi-google-tag-manager' ),
449
+ 'phase' => GTM4WP_PHASE_STABLE,
450
+ )
451
+ );
452
+
453
+ function gtm4wp_admin_output_section( $args ) {
454
+ echo '<span class="tabinfo">';
455
+
456
+ switch ( $args['id'] ) {
457
+ case GTM4WP_ADMIN_GROUP_GENERAL: {
458
+ _e( 'This plugin is intended to be used by IT girls&guys and marketing staff. Please be sure you read the <a href="https://developers.google.com/tag-manager/" target="_blank" rel="noopener">Google Tag Manager Help Center</a> before you start using this plugin.<br /><br />', 'duracelltomi-google-tag-manager' );
459
+
460
+ break;
461
+ }
462
+
463
+ case GTM4WP_ADMIN_GROUP_INCLUDES: {
464
+ _e( 'Here you can check what data is needed to be included in the dataLayer to be able to access them in Google Tag Manager', 'duracelltomi-google-tag-manager' );
465
+ echo '<br />';
466
+ printf( __( '* Browser, OS and Device data is provided using <a href="%s">WhichBrowser</a> library.', 'duracelltomi-google-tag-manager' ), 'http://whichbrowser.net/' );
467
+
468
+ break;
469
+ }
470
+
471
+ case GTM4WP_ADMIN_GROUP_EVENTS: {
472
+ _e( 'Fire tags in Google Tag Manager on special events on your website', 'duracelltomi-google-tag-manager' );
473
+
474
+ break;
475
+ }
476
+
477
+ case GTM4WP_ADMIN_GROUP_SCROLLER: {
478
+ _e( 'Fire tags based on how the visitor scrolls through your page.', 'duracelltomi-google-tag-manager' );
479
+ echo '<br />';
480
+ printf( __( 'Based on the script originaly posted to <a href="%s">Analytics Talk</a>', 'duracelltomi-google-tag-manager' ), 'http://cutroni.com/blog/2012/02/21/advanced-content-tracking-with-google-analytics-part-1/' );
481
+
482
+ break;
483
+ }
484
+
485
+ case GTM4WP_ADMIN_GROUP_BLACKLIST: {
486
+ _e( 'Here you can control which types of tags, triggers and variables can be executed on your site regardless of what tags are included in your container on the Google Tag Manager site. Use this to increase security!', 'duracelltomi-google-tag-manager' );
487
+ echo '<br />';
488
+ _e( 'Do not modify if you do not know what to do, since it can cause issues with your tag deployment!', 'duracelltomi-google-tag-manager' );
489
+ echo '<br />';
490
+ _e( 'For example blacklisting everything and only whitelisting the Google Analytics tag without whitelisting the URL variable type will cause your Google Analytics tags to be blocked anyway since the attached triggers (Page View) can not fire!', 'duracelltomi-google-tag-manager' );
491
+
492
+ break;
493
+ }
494
+
495
+ case GTM4WP_ADMIN_GROUP_INTEGRATION: {
496
+ _e( 'Google Tag Manager for WordPress can integrate with several popular plugins. Please check the plugins you would like to integrate with:', 'duracelltomi-google-tag-manager' );
497
+
498
+ break;
499
+ }
500
+
501
+ case GTM4WP_ADMIN_GROUP_ADVANCED: {
502
+ _e( 'You usually do not need to modify thoose settings. Please be carefull while hacking here.', 'duracelltomi-google-tag-manager' );
503
+
504
+ break;
505
+ }
506
+
507
+ case GTM4WP_ADMIN_GROUP_CREDITS: {
508
+ _e( 'Some info about the author of this plugin', 'duracelltomi-google-tag-manager' );
509
+
510
+ break;
511
+ }
512
+ } // end switch
513
+
514
+ echo '</span>';
515
+ }
516
+
517
+ function gtm4wp_admin_output_field( $args ) {
518
+ global $gtm4wp_options, $gtm4wp_business_verticals;
519
+
520
+ switch ( $args['label_for'] ) {
521
+ case GTM4WP_ADMIN_GROUP_GTMID: {
522
+ if ( defined( 'GTM4WP_HARDCODED_GTM_ID' ) ) {
523
+ $_gtm_id_value = GTM4WP_HARDCODED_GTM_ID;
524
+ $_input_readonly = ' readonly="readonly"';
525
+ $_warning_after = '<br /><span class="gtm_wpconfig_set">WARNING! Container ID was set and fixed in wp-config.php. If you wish to change this value, please edit your wp-config.php and change the container ID or remove the GTM4WP_HARDCODED_GTM_ID constant!</span>';
526
+ } else {
527
+ $_gtm_id_value = $gtm4wp_options[ GTM4WP_OPTION_GTM_CODE ];
528
+ $_input_readonly = '';
529
+ $_warning_after = '';
530
+ }
531
+
532
+ echo '<input type="text" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_GTM_CODE . ']" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_GTM_CODE . ']" value="' . $_gtm_id_value . '" ' . $_input_readonly . '/><br />' . $args['description'];
533
+ echo $_warning_after;
534
+ echo '<br /><span class="gtmid_validation_error">' . __( 'This does not seems to be a valid Google Tag Manager ID! Valid format: GTM-XXXXX where X can be numbers and capital letters. Use comma without any space (,) to enter multpile container IDs.', 'duracelltomi-google-tag-manager' ) . '</span>';
535
+
536
+ break;
537
+ }
538
+
539
+ case GTM4WP_ADMIN_GROUP_PLACEMENT: {
540
+ echo '<input type="radio" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_GTM_PLACEMENT . ']_' . GTM4WP_PLACEMENT_FOOTER . '" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_GTM_PLACEMENT . ']" value="' . GTM4WP_PLACEMENT_FOOTER . '" ' . ( $gtm4wp_options[ GTM4WP_OPTION_GTM_PLACEMENT ] == GTM4WP_PLACEMENT_FOOTER ? 'checked="checked"' : '' ) . '/> ' . __( 'Footer of the page (not recommended by Google, no tweak in your template required)', 'duracelltomi-google-tag-manager' ) . '<br />';
541
+ echo '<input type="radio" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_GTM_PLACEMENT . ']_' . GTM4WP_PLACEMENT_BODYOPEN . '" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_GTM_PLACEMENT . ']" value="' . GTM4WP_PLACEMENT_BODYOPEN . '" ' . ( $gtm4wp_options[ GTM4WP_OPTION_GTM_PLACEMENT ] == GTM4WP_PLACEMENT_BODYOPEN ? 'checked="checked"' : '' ) . '/> ' . __( 'Custom (needs tweak in your template)', 'duracelltomi-google-tag-manager' ) . '<br />';
542
+ echo '<input type="radio" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_GTM_PLACEMENT . ']_' . GTM4WP_PLACEMENT_BODYOPEN_AUTO . '" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_GTM_PLACEMENT . ']" value="' . GTM4WP_PLACEMENT_BODYOPEN_AUTO . '" ' . ( $gtm4wp_options[ GTM4WP_OPTION_GTM_PLACEMENT ] == GTM4WP_PLACEMENT_BODYOPEN_AUTO ? 'checked="checked"' : '' ) . '/> ' . __( 'Codeless injection (no tweak, right placement but experimental, could break your frontend)', 'duracelltomi-google-tag-manager' ) . '<br />';
543
+ echo '<input type="radio" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_GTM_PLACEMENT . ']_' . GTM4WP_PLACEMENT_OFF . '" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_GTM_PLACEMENT . ']" value="' . GTM4WP_PLACEMENT_OFF . '" ' . ( $gtm4wp_options[ GTM4WP_OPTION_GTM_PLACEMENT ] == GTM4WP_PLACEMENT_OFF ? 'checked="checked"' : '' ) . '/> ' . __( 'Off (only add data layer to the page source)', 'duracelltomi-google-tag-manager' ) . '<br /><br />' . $args['description'];
544
+
545
+ break;
546
+ }
547
+
548
+ case GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_DATALAYER_NAME . ']': {
549
+ echo '<input type="text" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_DATALAYER_NAME . ']" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_DATALAYER_NAME . ']" value="' . $gtm4wp_options[ GTM4WP_OPTION_DATALAYER_NAME ] . '" /><br />' . $args['description'];
550
+ echo '<br /><span class="datalayername_validation_error">' . __( 'This does not seems to be a valid JavaScript variable name! Please check and try again', 'duracelltomi-google-tag-manager' ) . '</span>';
551
+
552
+ break;
553
+ }
554
+
555
+ case GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_ENV_GTM_AUTH . ']': {
556
+ if ( defined( 'GTM4WP_HARDCODED_GTM_ENV_AUTH' ) ) {
557
+ $_gtm_auth_value = GTM4WP_HARDCODED_GTM_ENV_AUTH;
558
+ $_input_readonly = ' readonly="readonly"';
559
+ $_warning_after = '<br /><span class="gtm_wpconfig_set">WARNING! Environment auth parameter was set and fixed in wp-config.php. If you wish to change this value, please edit your wp-config.php and change the parameter value or remove the GTM4WP_HARDCODED_GTM_ENV_AUTH constant!</span>';
560
+ } else {
561
+ $_gtm_auth_value = $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_AUTH ];
562
+ $_input_readonly = '';
563
+ $_warning_after = '';
564
+ }
565
+
566
+ echo '<input type="text" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_ENV_GTM_AUTH . ']" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_ENV_GTM_AUTH . ']" value="' . $_gtm_auth_value . '" ' . $_input_readonly . '/><br />' . $args['description'];
567
+ echo $_warning_after;
568
+ echo '<br /><span class="gtmauth_validation_error">' . __( 'This does not seems to be a valid gtm_auth parameter! It should only contain letters, number and the &quot;-&quot; character. Please check and try again', 'duracelltomi-google-tag-manager' ) . '</span>';
569
+
570
+ break;
571
+ }
572
+
573
+ case GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_ENV_GTM_PREVIEW . ']': {
574
+ if ( defined( 'GTM4WP_HARDCODED_GTM_ENV_PREVIEW' ) ) {
575
+ $_gtm_preview_value = GTM4WP_HARDCODED_GTM_ENV_PREVIEW;
576
+ $_input_readonly = ' readonly="readonly"';
577
+ $_warning_after = '<br /><span class="gtm_wpconfig_set">WARNING! Environment preview parameter was set and fixed in wp-config.php. If you wish to change this value, please edit your wp-config.php and change the parameter value or remove the GTM4WP_HARDCODED_GTM_ENV_PREVIEW constant!</span>';
578
+ } else {
579
+ $_gtm_preview_value = $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_PREVIEW ];
580
+ $_input_readonly = '';
581
+ $_warning_after = '';
582
+ }
583
+
584
+ echo '<input type="text" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_ENV_GTM_PREVIEW . ']" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_ENV_GTM_PREVIEW . ']" value="' . $_gtm_preview_value . '" ' . $_input_readonly . '/><br />' . $args['description'];
585
+ echo $_warning_after;
586
+ echo '<br /><span class="gtmpreview_validation_error">' . __( 'This does not seems to be a valid gtm_preview parameter! It should have the format &quot;env-NN&quot; where NN is an integer number. Please check and try again', 'duracelltomi-google-tag-manager' ) . '</span>';
587
+
588
+ break;
589
+ }
590
+
591
+ case GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_BLACKLIST_ENABLE . ']': {
592
+ echo '<input type="radio" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_BLACKLIST_ENABLE . ']_0" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_BLACKLIST_ENABLE . ']" value="0" ' . ( $gtm4wp_options[ GTM4WP_OPTION_BLACKLIST_ENABLE ] == 0 ? 'checked="checked"' : '' ) . '/> ' . __( 'Disable feature: control everything on Google Tag Manager interface', 'duracelltomi-google-tag-manager' ) . '<br />';
593
+ echo '<input type="radio" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_BLACKLIST_ENABLE . ']_1" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_BLACKLIST_ENABLE . ']" value="1" ' . ( $gtm4wp_options[ GTM4WP_OPTION_BLACKLIST_ENABLE ] == 1 ? 'checked="checked"' : '' ) . '/> ' . __( 'Allow all, except the checked items on all blacklist tabs (blacklist)', 'duracelltomi-google-tag-manager' ) . '<br />';
594
+ echo '<input type="radio" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_BLACKLIST_ENABLE . ']_2" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_BLACKLIST_ENABLE . ']" value="2" ' . ( $gtm4wp_options[ GTM4WP_OPTION_BLACKLIST_ENABLE ] == 2 ? 'checked="checked"' : '' ) . '/> ' . __( 'Block all, except the checked items on all blacklist tabs (whitelist)', 'duracelltomi-google-tag-manager' ) . '<br />';
595
+ echo $args['description'];
596
+
597
+ break;
598
+ }
599
+
600
+ case GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_INCLUDE_WEATHERUNITS . ']': {
601
+ echo '<input type="radio" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_INCLUDE_WEATHERUNITS . ']_0" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_INCLUDE_WEATHERUNITS . ']" value="0" ' . ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_WEATHERUNITS ] == 0 ? 'checked="checked"' : '' ) . '/> ' . __( 'Celsius', 'duracelltomi-google-tag-manager' ) . '<br />';
602
+ echo '<input type="radio" id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_INCLUDE_WEATHERUNITS . ']_1" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_INCLUDE_WEATHERUNITS . ']" value="1" ' . ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_WEATHERUNITS ] == 1 ? 'checked="checked"' : '' ) . '/> ' . __( 'Fahrenheit', 'duracelltomi-google-tag-manager' ) . '<br />';
603
+ echo $args['description'];
604
+
605
+ break;
606
+ }
607
+
608
+ case GTM4WP_ADMIN_GROUP_INFO: {
609
+ echo $args['description'];
610
+
611
+ break;
612
+ }
613
+
614
+ case GTM4WP_OPTIONS . "[" . GTM4WP_OPTION_INTEGRATE_WCEECBRANDTAXONOMY . "]": {
615
+ echo '<select id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_INTEGRATE_WCEECBRANDTAXONOMY . ']" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_INTEGRATE_WCEECBRANDTAXONOMY . ']">';
616
+ echo '<option value="">(not set)</option>';
617
+
618
+ $gtm4wp_taxonomies = get_taxonomies(array(
619
+ "show_ui" => true,
620
+ "public" => true,
621
+ "_builtin" => false
622
+ ), "object", "and");
623
+
624
+ foreach( $gtm4wp_taxonomies as $onetaxonomy ) {
625
+ echo '<option value="' . $onetaxonomy->name . '"' . ( $gtm4wp_options[GTM4WP_OPTION_INTEGRATE_WCEECBRANDTAXONOMY] === $onetaxonomy->name ? ' selected="selected"' : '' ) . '>' . $onetaxonomy->label . '</option>';
626
+ }
627
+
628
+ echo '</select>';
629
+
630
+ break;
631
+ }
632
+
633
+ case GTM4WP_OPTIONS . "[" . GTM4WP_OPTION_INTEGRATE_WCBUSINESSVERTICAL . "]": {
634
+ echo '<select id="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_INTEGRATE_WCBUSINESSVERTICAL . ']" name="' . GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_INTEGRATE_WCBUSINESSVERTICAL . ']">';
635
+
636
+ foreach( $gtm4wp_business_verticals as $vertical_id => $vertical_display_name ) {
637
+ echo '<option value="' . $vertical_id . '"' . ( $gtm4wp_options[GTM4WP_OPTION_INTEGRATE_WCBUSINESSVERTICAL] === $vertical_id ? ' selected="selected"' : '' ) . '>' . $vertical_display_name . '</option>';
638
+ }
639
+
640
+ echo '</select><br>' . $args['description'];
641
+
642
+ break;
643
+ }
644
+
645
+ default: {
646
+ if ( preg_match( '/' . GTM4WP_OPTIONS . "\\[blacklist\\-[^\\]]+\\]/i", $args['label_for'] ) ) {
647
+ if ( 'blacklist-sandboxed' == $args['entityid'] ) {
648
+ echo '<input type="checkbox" id="' . $args['label_for'] . '" name="' . $args['label_for'] . '" value="1" ' . checked( 1, $gtm4wp_options[ GTM4WP_OPTION_BLACKLIST_SANDBOXED ], false ) . ' /><br />' . $args['description'];
649
+ } else {
650
+ echo '<input type="checkbox" id="' . $args['label_for'] . '" name="' . $args['label_for'] . '" value="1" ' . checked( 1, in_array( $args['entityid'], $gtm4wp_options[ GTM4WP_OPTION_BLACKLIST_STATUS ] ), false ) . ' /><br />' . $args['description'];
651
+ }
652
+ } else {
653
+ $optval = $gtm4wp_options[ $args['optionfieldid'] ];
654
+
655
+ switch ( gettype( $optval ) ) {
656
+ case 'boolean': {
657
+ echo '<input type="checkbox" id="' . GTM4WP_OPTIONS . '[' . $args['optionfieldid'] . ']" name="' . GTM4WP_OPTIONS . '[' . $args['optionfieldid'] . ']" value="1" ' . checked( 1, $optval, false ) . ' /><br />' . $args['description'];
658
+
659
+ if ( isset( $args['plugintocheck'] ) && ( $args['plugintocheck'] != '' ) ) {
660
+ if ( is_plugin_active( $args['plugintocheck'] ) ) {
661
+ echo '<br />' . __( 'This plugin is <strong class="gtm4wp-plugin-active">active</strong>, it is strongly recommended to enable this integration!', 'duracelltomi-google-tag-manager' );
662
+ } else {
663
+ echo '<br />' . __( 'This plugin (' . $args['plugintocheck'] . ') is <strong class="gtm4wp-plugin-not-active">not active</strong>, enabling this integration could cause issues on frontend!', 'duracelltomi-google-tag-manager' );
664
+ }
665
+ }
666
+
667
+ break;
668
+ }
669
+
670
+ case 'integer': {
671
+ echo '<input type="number" step="1" min="0" class="small-text" id="' . GTM4WP_OPTIONS . '[' . $args['optionfieldid'] . ']" name="' . GTM4WP_OPTIONS . '[' . $args['optionfieldid'] . ']" value="' . esc_attr( $optval ) . '" /><br />' . $args['description'];
672
+
673
+ if ( isset( $args['plugintocheck'] ) && ( $args['plugintocheck'] != '' ) ) {
674
+ if ( is_plugin_active( $args['plugintocheck'] ) ) {
675
+ echo '<br />' . __( 'This plugin is <strong class="gtm4wp-plugin-active">active</strong>, it is strongly recommended to enable this integration!', 'duracelltomi-google-tag-manager' );
676
+ } else {
677
+ echo '<br />' . __( 'This plugin is <strong class="gtm4wp-plugin-not-active">not active</strong>, enabling this integration could cause issues on frontend!', 'duracelltomi-google-tag-manager' );
678
+ }
679
+ }
680
+
681
+ break;
682
+ }
683
+
684
+ default : {
685
+ echo '<input type="text" id="' . GTM4WP_OPTIONS . '[' . $args['optionfieldid'] . ']" name="' . GTM4WP_OPTIONS . '[' . $args['optionfieldid'] . ']" value="' . esc_attr( $optval ) . '" size="80" /><br />' . $args['description'];
686
+
687
+ if ( isset( $args['plugintocheck'] ) && ( $args['plugintocheck'] != '' ) ) {
688
+ if ( is_plugin_active( $args['plugintocheck'] ) ) {
689
+ echo '<br />' . __( 'This plugin is <strong class="gtm4wp-plugin-active">active</strong>, it is strongly recommended to enable this integration!', 'duracelltomi-google-tag-manager' );
690
+ } else {
691
+ echo '<br />' . __( 'This plugin is <strong class="gtm4wp-plugin-not-active">not active</strong>, enabling this integration could cause issues on frontend!', 'duracelltomi-google-tag-manager' );
692
+ }
693
+ }
694
+ }
695
+ } // end switch gettype optval
696
+ }
697
+ }
698
+ } // end switch
699
+ }
700
+
701
+ function gtm4wp_sanitize_options( $options ) {
702
+ global $wpdb, $gtm4wp_entity_ids;
703
+
704
+ $output = gtm4wp_reload_options();
705
+
706
+ foreach ( $output as $optionname => $optionvalue ) {
707
+ if ( isset( $options[ $optionname ] ) ) {
708
+ $newoptionvalue = $options[ $optionname ];
709
+ } else {
710
+ $newoptionvalue = '';
711
+ }
712
+
713
+ // "include" settings
714
+ if ( substr( $optionname, 0, 8 ) == 'include-' ) {
715
+ $output[ $optionname ] = (bool) $newoptionvalue;
716
+
717
+ // dataLayer events
718
+ } elseif ( substr( $optionname, 0, 6 ) == 'event-' ) {
719
+ $output[ $optionname ] = (bool) $newoptionvalue;
720
+
721
+ // clear oembed transients when feature is enabled because we need to hook into the oembed process to enable some 3rd party APIs
722
+ if ( $output[ $optionname ] && ! $optionvalue ) {
723
+ if ( GTM4WP_OPTION_EVENTS_YOUTUBE == $optionname ) {
724
+ $wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_value LIKE '%youtube.com%' AND meta_key LIKE '_oembed_%'" );
725
+ }
726
+
727
+ if ( GTM4WP_OPTION_EVENTS_VIMEO == $optionname ) {
728
+ $wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_value LIKE '%vimeo.com%' AND meta_key LIKE '_oembed_%'" );
729
+ }
730
+ }
731
+
732
+ // blacklist / whitelist entities
733
+ } elseif ( substr( $optionname, 0, 10 ) == 'blacklist-' ) {
734
+ if ( GTM4WP_OPTION_BLACKLIST_ENABLE === $optionname ) {
735
+ $output[ $optionname ] = (int) $options[ GTM4WP_OPTION_BLACKLIST_ENABLE ];
736
+ } else if ( GTM4WP_OPTION_BLACKLIST_SANDBOXED == $optionname ) {
737
+ $output[ $optionname ] = (bool) $newoptionvalue;
738
+ } else if ( GTM4WP_OPTION_BLACKLIST_STATUS == $optionname ) {
739
+ $selected_blacklist_entities = array();
740
+
741
+ foreach( $gtm4wp_entity_ids as $gtm_entity_group_id => $gtm_entity_group_list ) {
742
+ foreach( $gtm_entity_group_list as $gtm_entity_id => $gtm_entity_label ) {
743
+ $entity_option_id = 'blacklist-' . $gtm_entity_group_id . '-' . $gtm_entity_id;
744
+ if ( array_key_exists( $entity_option_id, $options ) ) {
745
+ $newoptionvalue = (bool) $options[ $entity_option_id ];
746
+ if ( $newoptionvalue ) {
747
+ $selected_blacklist_entities[] = $gtm_entity_id;
748
+ }
749
+ }
750
+ }
751
+ }
752
+
753
+ $output[ $optionname ] = implode( ',', $selected_blacklist_entities );
754
+ }
755
+
756
+ // Google Optimize settings
757
+ } elseif ( $optionname == GTM4WP_OPTION_INTEGRATE_GOOGLEOPTIMIZEIDS ) {
758
+ $_goid_val = trim( $newoptionvalue );
759
+ if ( '' == $_goid_val ) {
760
+ $_goid_list = array();
761
+ } else {
762
+ $_goid_list = explode( ',', $_goid_val );
763
+ }
764
+ $_goid_haserror = false;
765
+
766
+ foreach ( $_goid_list as $one_go_id ) {
767
+ $_goid_haserror = $_goid_haserror || ! preg_match( '/^(GTM|OPT)-[A-Z0-9]+$/', $one_go_id );
768
+ }
769
+
770
+ if ( $_goid_haserror && ( count( $_goid_list ) > 0 ) ) {
771
+ add_settings_error( GTM4WP_ADMIN_GROUP, GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_INTEGRATE_GOOGLEOPTIMIZEIDS . ']', __( 'Invalid Google Optimize ID. Valid ID format: GTM-XXXXX or OPT-XXXXX. Use comma without additional space (,) to enter more than one ID.', 'duracelltomi-google-tag-manager' ) );
772
+ } else {
773
+ $output[ $optionname ] = $newoptionvalue;
774
+ }
775
+ } elseif ( $optionname == GTM4WP_OPTION_INTEGRATE_GOOGLEOPTIMIZETIMEOUT ) {
776
+ $output[ $optionname ] = (int) $newoptionvalue;
777
+
778
+ } elseif ( $optionname == GTM4WP_OPTION_INTEGRATE_WCPRODPERIMPRESSION ) {
779
+ $output[ $optionname ] = (int) $newoptionvalue;
780
+
781
+ } elseif ( $optionname == GTM4WP_OPTION_INTEGRATE_WCORDERMAXAGE ) {
782
+ $output[ $optionname ] = (int) $newoptionvalue;
783
+
784
+ }elseif ( $optionname == GTM4WP_OPTION_INTEGRATE_WCREMPRODIDPREFIX ) {
785
+ $output[ $optionname ] = trim( (string) $newoptionvalue );
786
+
787
+ } else if ( $optionname == GTM4WP_OPTION_INTEGRATE_WCEECBRANDTAXONOMY ) {
788
+ $output[$optionname] = trim( (string) $newoptionvalue );
789
+
790
+ } else if ( $optionname == GTM4WP_OPTION_INTEGRATE_WCBUSINESSVERTICAL ) {
791
+ $output[$optionname] = trim( (string) $newoptionvalue );
792
+
793
+ } else if ( $optionname == GTM4WP_OPTION_GTMDOMAIN ) {
794
+ // for PHP 7- compatibility
795
+ if ( !defined("FILTER_FLAG_HOSTNAME") ) {
796
+ define( "FILTER_FLAG_HOSTNAME", 0 );
797
+ }
798
+
799
+ $newoptionvalue = filter_var( $newoptionvalue, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME );
800
+ if ( $newoptionvalue === false ) {
801
+ $newoptionvalue = '';
802
+ }
803
+ $output[$optionname] = trim( (string) $newoptionvalue );
804
+
805
+ // Accelerated Mobile Pages settings
806
+ } elseif ( $optionname == GTM4WP_OPTION_INTEGRATE_AMPID ) {
807
+ $_ampid_val = trim( $newoptionvalue );
808
+ if ( '' == $_ampid_val ) {
809
+ $_ampid_list = array();
810
+ } else {
811
+ $_ampid_list = explode( ',', $_ampid_val );
812
+ }
813
+ $_ampid_haserror = false;
814
+
815
+ foreach ( $_ampid_list as $one_amp_id ) {
816
+ $_ampid_haserror = $_ampid_haserror || ! preg_match( '/^GTM-[A-Z0-9]+$/', $one_amp_id );
817
+ }
818
+
819
+ if ( $_ampid_haserror && ( count( $_ampid_list ) > 0 ) ) {
820
+ add_settings_error( GTM4WP_ADMIN_GROUP, GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_INTEGRATE_AMPID . ']', __( 'Invalid AMP Google Tag Manager Container ID. Valid ID format: GTM-XXXXX. Use comma without additional space (,) to enter more than one ID.', 'duracelltomi-google-tag-manager' ) );
821
+ } else {
822
+ $output[ $optionname ] = $newoptionvalue;
823
+ }
824
+
825
+ // integrations
826
+ } elseif ( substr( $optionname, 0, 10 ) == 'integrate-' ) {
827
+ $output[ $optionname ] = (bool) $newoptionvalue;
828
+
829
+ // GTM code or dataLayer variable name
830
+ } elseif ( ( $optionname == GTM4WP_OPTION_GTM_CODE ) || ( $optionname == GTM4WP_OPTION_DATALAYER_NAME ) || ( $optionname == GTM4WP_OPTION_ENV_GTM_AUTH ) || ( $optionname == GTM4WP_OPTION_ENV_GTM_PREVIEW ) ) {
831
+ $newoptionvalue = trim( $newoptionvalue );
832
+
833
+ if ( $optionname == GTM4WP_OPTION_GTM_CODE ) {
834
+ $_gtmid_list = explode( ',', $newoptionvalue );
835
+ $_gtmid_haserror = false;
836
+
837
+ foreach ( $_gtmid_list as $one_gtm_id ) {
838
+ $_gtmid_haserror = $_gtmid_haserror || ! preg_match( '/^GTM-[A-Z0-9]+$/', $one_gtm_id );
839
+ }
840
+
841
+ if ( $_gtmid_haserror ) {
842
+ add_settings_error( GTM4WP_ADMIN_GROUP, GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_GTM_CODE . ']', __( 'Invalid Google Tag Manager ID. Valid ID format: GTM-XXXXX. Use comma without additional space (,) to enter more than one container ID.', 'duracelltomi-google-tag-manager' ) );
843
+ } else {
844
+ $output[ $optionname ] = $newoptionvalue;
845
+ }
846
+ } elseif ( ( $optionname == GTM4WP_OPTION_DATALAYER_NAME ) && ( $newoptionvalue != '' ) && ( ! preg_match( '/^[a-zA-Z][a-zA-Z0-9_-]*$/', $newoptionvalue ) ) ) {
847
+ add_settings_error( GTM4WP_ADMIN_GROUP, GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_DATALAYER_NAME . ']', __( "Invalid dataLayer variable name. Please start with a character from a-z or A-Z followed by characters from a-z, A-Z, 0-9 or '_' or '-'!", 'duracelltomi-google-tag-manager' ) );
848
+
849
+ } elseif ( ( $optionname == GTM4WP_OPTION_ENV_GTM_AUTH ) && ( $newoptionvalue != '' ) && ( ! preg_match( '/^[a-zA-Z0-9-_]+$/', $newoptionvalue ) ) ) {
850
+ add_settings_error( GTM4WP_ADMIN_GROUP, GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_ENV_GTM_AUTH . ']', __( "Invalid gtm_auth environment parameter value. It should only contain letters, numbers or the '-' and '_' characters.", 'duracelltomi-google-tag-manager' ) );
851
+
852
+ } elseif ( ( $optionname == GTM4WP_OPTION_ENV_GTM_PREVIEW ) && ( $newoptionvalue != '' ) && ( ! preg_match( '/^env-[0-9]+$/', $newoptionvalue ) ) ) {
853
+ add_settings_error( GTM4WP_ADMIN_GROUP, GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_ENV_GTM_PREVIEW . ']', __( "Invalid gtm_preview environment parameter value. It should have the format 'env-NN' where NN is an integer number.", 'duracelltomi-google-tag-manager' ) );
854
+
855
+ } else {
856
+ $output[ $optionname ] = $newoptionvalue;
857
+ }
858
+
859
+ // GTM container code placement
860
+ } elseif ( $optionname == GTM4WP_OPTION_GTM_PLACEMENT ) {
861
+ $output[ $optionname ] = (int) $newoptionvalue;
862
+ if ( ( $output[ $optionname ] < 0 ) || ( $output[ $optionname ] > 3 ) ) {
863
+ $output[ $optionname ] = 0;
864
+ }
865
+
866
+ // scroll tracking content ID
867
+ } elseif ( $optionname == GTM4WP_OPTION_SCROLLER_CONTENTID ) {
868
+ $output[ $optionname ] = trim( str_replace( '#', '', $newoptionvalue ) );
869
+
870
+ // anything else
871
+ } else {
872
+ switch ( gettype( $optionvalue ) ) {
873
+ case 'boolean': {
874
+ $output[ $optionname ] = (bool) $newoptionvalue;
875
+
876
+ break;
877
+ }
878
+
879
+ case 'integer': {
880
+ $output[ $optionname ] = (int) $newoptionvalue;
881
+
882
+ break;
883
+ }
884
+
885
+ default: {
886
+ $output[ $optionname ] = $newoptionvalue;
887
+ }
888
+ } // end switch
889
+ }
890
+ }
891
+
892
+ return $output;
893
+ }
894
+
895
+ function gtm4wp_admin_init() {
896
+ global $gtm4wp_includefieldtexts, $gtm4wp_eventfieldtexts, $gtm4wp_integratefieldtexts, $gtm4wp_scrollerfieldtexts,
897
+ $gtm4wp_advancedfieldtexts, $gtm4wp_entity_ids;
898
+
899
+ register_setting( GTM4WP_ADMIN_GROUP, GTM4WP_OPTIONS, 'gtm4wp_sanitize_options' );
900
+
901
+ add_settings_section(
902
+ GTM4WP_ADMIN_GROUP_GENERAL,
903
+ __( 'General', 'duracelltomi-google-tag-manager' ),
904
+ 'gtm4wp_admin_output_section',
905
+ GTM4WP_ADMINSLUG
906
+ );
907
+
908
+ add_settings_field(
909
+ GTM4WP_ADMIN_GROUP_GTMID,
910
+ __( 'Google Tag Manager ID', 'duracelltomi-google-tag-manager' ),
911
+ 'gtm4wp_admin_output_field',
912
+ GTM4WP_ADMINSLUG,
913
+ GTM4WP_ADMIN_GROUP_GENERAL,
914
+ array(
915
+ 'label_for' => GTM4WP_ADMIN_GROUP_GTMID,
916
+ 'description' => __( 'Enter your Google Tag Manager ID here. Use comma without space (,) to enter multiple IDs.', 'duracelltomi-google-tag-manager' ),
917
+ )
918
+ );
919
+
920
+ add_settings_field(
921
+ GTM4WP_ADMIN_GROUP_PLACEMENT,
922
+ __( 'Container code <code>&lt;noscript&gt;</code> part placement', 'duracelltomi-google-tag-manager' ),
923
+ 'gtm4wp_admin_output_field',
924
+ GTM4WP_ADMINSLUG,
925
+ GTM4WP_ADMIN_GROUP_GENERAL,
926
+ array(
927
+ 'label_for' => GTM4WP_ADMIN_GROUP_PLACEMENT,
928
+ 'description' => __( "Code placement decides where to put the second, so called noscript part of the GTM container code.<br />This code is usually only executed if your visitor has for some reason disabled JavaScript.<br/>The main GTM container code will be placed into the <code>&lt;head&gt;</code> section of your webpages anyway (where it belongs to).<br />If you select 'Custom' you need to edit your template file and add the following line just after the opening <code>&lt;body&gt;</code> tag:<br /><code>&lt;?php if ( function_exists( 'gtm4wp_the_gtm_tag' ) ) { gtm4wp_the_gtm_tag(); } ?&gt;</code>", 'duracelltomi-google-tag-manager' ),
929
+ )
930
+ );
931
+
932
+ add_settings_section(
933
+ GTM4WP_ADMIN_GROUP_INCLUDES,
934
+ __( 'Basic data', 'duracelltomi-google-tag-manager' ),
935
+ 'gtm4wp_admin_output_section',
936
+ GTM4WP_ADMINSLUG
937
+ );
938
+
939
+ foreach ( $gtm4wp_includefieldtexts as $fieldid => $fielddata ) {
940
+ $phase = isset( $fielddata['phase'] ) ? $fielddata['phase'] : GTM4WP_PHASE_STABLE;
941
+
942
+ add_settings_field(
943
+ 'gtm4wp-admin-' . $fieldid . '-id',
944
+ $fielddata['label'] . '<span class="' . $phase . '"></span>',
945
+ 'gtm4wp_admin_output_field',
946
+ GTM4WP_ADMINSLUG,
947
+ GTM4WP_ADMIN_GROUP_INCLUDES,
948
+ array(
949
+ 'label_for' => 'gtm4wp-options[' . $fieldid . ']',
950
+ 'description' => $fielddata['description'],
951
+ 'optionfieldid' => $fieldid,
952
+ )
953
+ );
954
+ }
955
+
956
+ add_settings_section(
957
+ GTM4WP_ADMIN_GROUP_EVENTS,
958
+ __( 'Events', 'duracelltomi-google-tag-manager' ),
959
+ 'gtm4wp_admin_output_section',
960
+ GTM4WP_ADMINSLUG
961
+ );
962
+
963
+ foreach ( $gtm4wp_eventfieldtexts as $fieldid => $fielddata ) {
964
+ $phase = isset( $fielddata['phase'] ) ? $fielddata['phase'] : GTM4WP_PHASE_STABLE;
965
+
966
+ add_settings_field(
967
+ 'gtm4wp-admin-' . $fieldid . '-id',
968
+ $fielddata['label'] . '<span class="' . $phase . '"></span>',
969
+ 'gtm4wp_admin_output_field',
970
+ GTM4WP_ADMINSLUG,
971
+ GTM4WP_ADMIN_GROUP_EVENTS,
972
+ array(
973
+ 'label_for' => 'gtm4wp-options[' . $fieldid . ']',
974
+ 'description' => $fielddata['description'],
975
+ 'optionfieldid' => $fieldid,
976
+ )
977
+ );
978
+ }
979
+
980
+ add_settings_section(
981
+ GTM4WP_ADMIN_GROUP_SCROLLER,
982
+ __( 'Scroll tracking', 'duracelltomi-google-tag-manager' ),
983
+ 'gtm4wp_admin_output_section',
984
+ GTM4WP_ADMINSLUG
985
+ );
986
+
987
+ foreach ( $gtm4wp_scrollerfieldtexts as $fieldid => $fielddata ) {
988
+ $phase = isset( $fielddata['phase'] ) ? $fielddata['phase'] : GTM4WP_PHASE_STABLE;
989
+
990
+ add_settings_field(
991
+ 'gtm4wp-admin-' . $fieldid . '-id',
992
+ $fielddata['label'] . '<span class="' . $phase . '"></span>',
993
+ 'gtm4wp_admin_output_field',
994
+ GTM4WP_ADMINSLUG,
995
+ GTM4WP_ADMIN_GROUP_SCROLLER,
996
+ array(
997
+ 'label_for' => 'gtm4wp-options[' . $fieldid . ']',
998
+ 'description' => $fielddata['description'],
999
+ 'optionfieldid' => $fieldid,
1000
+ )
1001
+ );
1002
+ }
1003
+
1004
+ add_settings_section(
1005
+ GTM4WP_ADMIN_GROUP_BLACKLIST,
1006
+ __( 'Security', 'duracelltomi-google-tag-manager' ),
1007
+ 'gtm4wp_admin_output_section',
1008
+ GTM4WP_ADMINSLUG
1009
+ );
1010
+
1011
+ add_settings_field(
1012
+ GTM4WP_OPTION_BLACKLIST_ENABLE,
1013
+ __( 'Enable blacklist/whitelist', 'duracelltomi-google-tag-manager' ),
1014
+ 'gtm4wp_admin_output_field',
1015
+ GTM4WP_ADMINSLUG,
1016
+ GTM4WP_ADMIN_GROUP_BLACKLIST,
1017
+ array(
1018
+ 'label_for' => GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_BLACKLIST_ENABLE . ']',
1019
+ 'description' => '',
1020
+ 'optionsfieldid' => GTM4WP_OPTION_BLACKLIST_ENABLE
1021
+ )
1022
+ );
1023
+
1024
+ add_settings_field(
1025
+ GTM4WP_OPTION_BLACKLIST_SANDBOXED,
1026
+ __( 'Custom tag/variable templates', 'duracelltomi-google-tag-manager' ),
1027
+ 'gtm4wp_admin_output_field',
1028
+ GTM4WP_ADMINSLUG,
1029
+ GTM4WP_ADMIN_GROUP_BLACKLIST,
1030
+ array(
1031
+ 'label_for' => GTM4WP_OPTIONS . '[' . GTM4WP_OPTION_BLACKLIST_SANDBOXED . ']',
1032
+ 'description' => '',
1033
+ 'entityid' => GTM4WP_OPTION_BLACKLIST_SANDBOXED
1034
+ )
1035
+ );
1036
+
1037
+ foreach( $gtm4wp_entity_ids as $gtm_entity_group_id => $gtm_entity_group_list ) {
1038
+ foreach( $gtm_entity_group_list as $gtm_entity_id => $gtm_entity_label ) {
1039
+ add_settings_field(
1040
+ 'gtm4wp-admin-blacklist-' . $gtm_entity_group_id . '-' . $gtm_entity_id . '-id',
1041
+ $gtm_entity_label,
1042
+ 'gtm4wp_admin_output_field',
1043
+ GTM4WP_ADMINSLUG,
1044
+ GTM4WP_ADMIN_GROUP_BLACKLIST,
1045
+ array(
1046
+ 'label_for' => 'gtm4wp-options[blacklist-' . $gtm_entity_group_id . '-' . $gtm_entity_id . ']',
1047
+ 'description' => '',
1048
+ 'entityid' => $gtm_entity_id,
1049
+ )
1050
+ );
1051
+ }
1052
+ }
1053
+
1054
+ add_settings_section(
1055
+ GTM4WP_ADMIN_GROUP_INTEGRATION,
1056
+ __( 'Integration', 'duracelltomi-google-tag-manager' ),
1057
+ 'gtm4wp_admin_output_section',
1058
+ GTM4WP_ADMINSLUG
1059
+ );
1060
+
1061
+ foreach ( $gtm4wp_integratefieldtexts as $fieldid => $fielddata ) {
1062
+ $phase = isset( $fielddata['phase'] ) ? $fielddata['phase'] : GTM4WP_PHASE_STABLE;
1063
+
1064
+ add_settings_field(
1065
+ 'gtm4wp-admin-' . $fieldid . '-id',
1066
+ $fielddata['label'] . '<span class="' . $phase . '"></span>',
1067
+ 'gtm4wp_admin_output_field',
1068
+ GTM4WP_ADMINSLUG,
1069
+ GTM4WP_ADMIN_GROUP_INTEGRATION,
1070
+ array(
1071
+ 'label_for' => 'gtm4wp-options[' . $fieldid . ']',
1072
+ 'description' => $fielddata['description'],
1073
+ 'optionfieldid' => $fieldid,
1074
+ 'plugintocheck' => isset( $fielddata['plugintocheck'] ) ? $fielddata['plugintocheck'] : '',
1075
+ )
1076
+ );
1077
+ }
1078
+
1079
+ add_settings_section(
1080
+ GTM4WP_ADMIN_GROUP_ADVANCED,
1081
+ __( 'Advanced', 'duracelltomi-google-tag-manager' ),
1082
+ 'gtm4wp_admin_output_section',
1083
+ GTM4WP_ADMINSLUG
1084
+ );
1085
+
1086
+ foreach ( $gtm4wp_advancedfieldtexts as $fieldid => $fielddata ) {
1087
+ $phase = isset( $fielddata['phase'] ) ? $fielddata['phase'] : GTM4WP_PHASE_STABLE;
1088
+
1089
+ add_settings_field(
1090
+ 'gtm4wp-admin-' . $fieldid . '-id',
1091
+ $fielddata['label'] . '<span class="' . $phase . '"></span>',
1092
+ 'gtm4wp_admin_output_field',
1093
+ GTM4WP_ADMINSLUG,
1094
+ GTM4WP_ADMIN_GROUP_ADVANCED,
1095
+ array(
1096
+ 'label_for' => 'gtm4wp-options[' . $fieldid . ']',
1097
+ 'description' => $fielddata['description'],
1098
+ 'optionfieldid' => $fieldid,
1099
+ 'plugintocheck' => isset( $fielddata['plugintocheck'] ) ? $fielddata['plugintocheck'] : '',
1100
+ )
1101
+ );
1102
+ }
1103
+
1104
+ add_settings_section(
1105
+ GTM4WP_ADMIN_GROUP_CREDITS,
1106
+ __( 'Credits', 'duracelltomi-google-tag-manager' ),
1107
+ 'gtm4wp_admin_output_section',
1108
+ GTM4WP_ADMINSLUG
1109
+ );
1110
+
1111
+ add_settings_field(
1112
+ GTM4WP_ADMIN_GROUP_INFO,
1113
+ __( 'Author', 'duracelltomi-google-tag-manager' ),
1114
+ 'gtm4wp_admin_output_field',
1115
+ GTM4WP_ADMINSLUG,
1116
+ GTM4WP_ADMIN_GROUP_CREDITS,
1117
+ array(
1118
+ 'label_for' => GTM4WP_ADMIN_GROUP_INFO,
1119
+ 'description' => '<strong>Thomas Geiger</strong><br />
1120
+ Website: <a href="https://gtm4wp.com/" target="_blank" rel="noopener">gtm4wp.com</a><br />
1121
+ <a href="https://www.linkedin.com/in/duracelltomi" target="_blank" rel="noopener">Me on LinkedIn</a><br />
1122
+ <a href="http://www.linkedin.com/company/jabjab-online-marketing-ltd" target="_blank" rel="noopener">JabJab Online Marketing on LinkedIn</a>',
1123
+ )
1124
+ );
1125
+
1126
+ // apply oembed code changes on the admin as well since the oembed call on the admin is cached by WordPress into a transient
1127
+ // that is applied on the frontend later
1128
+ require_once dirname( __FILE__ ) . '/../integration/youtube.php';
1129
+ require_once dirname( __FILE__ ) . '/../integration/vimeo.php';
1130
+ require_once dirname( __FILE__ ) . '/../integration/soundcloud.php';
1131
+ }
1132
+
1133
+ function gtm4wp_show_admin_page() {
1134
+ global $gtp4wp_plugin_url;
1135
+ ?>
1136
+ <div class="wrap">
1137
+ <div id="gtm4wp-icon" class="icon32" style="background-image: url(<?php echo $gtp4wp_plugin_url; ?>admin/images/tag_manager-32.png);"><br /></div>
1138
+ <h2><?php _e( 'Google Tag Manager for WordPress options', 'duracelltomi-google-tag-manager' ); ?></h2>
1139
+ <form action="options.php" method="post">
1140
+ <?php settings_fields( GTM4WP_ADMIN_GROUP ); ?>
1141
+ <?php do_settings_sections( GTM4WP_ADMINSLUG ); ?>
1142
+ <?php submit_button(); ?>
1143
+
1144
+ </form>
1145
+ </div>
1146
+ <?php
1147
+ }
1148
+
1149
+ function gtm4wp_add_admin_page() {
1150
+ add_options_page(
1151
+ __( 'Google Tag Manager for WordPress settings', 'duracelltomi-google-tag-manager' ),
1152
+ __( 'Google Tag Manager', 'duracelltomi-google-tag-manager' ),
1153
+ 'manage_options',
1154
+ GTM4WP_ADMINSLUG,
1155
+ 'gtm4wp_show_admin_page'
1156
+ );
1157
+ }
1158
+
1159
+ function gtm4wp_add_admin_js( $hook ) {
1160
+ global $gtp4wp_plugin_url;
1161
+
1162
+ if ( $hook == 'settings_page_' . GTM4WP_ADMINSLUG ) {
1163
+ wp_register_script( 'admin-subtabs', $gtp4wp_plugin_url . 'js/admin-subtabs.js', array(), GTM4WP_VERSION );
1164
+
1165
+ $subtabtexts = array(
1166
+ 'posttabtitle' => __( 'Posts', 'duracelltomi-google-tag-manager' ),
1167
+ 'searchtabtitle' => __( 'Search', 'duracelltomi-google-tag-manager' ),
1168
+ 'visitortabtitle' => __( 'Visitors', 'duracelltomi-google-tag-manager' ),
1169
+ 'adwordstabtitle' => __( 'Google Ads', 'duracelltomi-google-tag-manager' ),
1170
+ 'browsertabtitle' => __( 'Browser/OS/Device', 'duracelltomi-google-tag-manager' ),
1171
+ 'blocktagstabtitle' => __( 'Blacklist tags', 'duracelltomi-google-tag-manager' ),
1172
+ 'blocktriggerstabtitle' => __( 'Blacklist triggers', 'duracelltomi-google-tag-manager' ),
1173
+ 'blockmacrostabtitle' => __( 'Blacklist variables', 'duracelltomi-google-tag-manager' ),
1174
+ 'wpcf7tabtitle' => __( 'Contact Form 7', 'duracelltomi-google-tag-manager' ),
1175
+ 'wctabtitle' => __( 'WooCommerce', 'duracelltomi-google-tag-manager' ),
1176
+ 'gotabtitle' => __( 'Google Optimize', 'duracelltomi-google-tag-manager' ),
1177
+ 'amptabtitle' => __( 'Accelerated Mobile Pages', 'duracelltomi-google-tag-manager' ),
1178
+ 'cookiebottabtitle' => __( 'Cookiebot', 'duracelltomi-google-tag-manager' ),
1179
+ 'weathertabtitle' => __( 'Weather & geo data', 'duracelltomi-google-tag-manager' ),
1180
+ 'generaleventstabtitle' => __( 'General events', 'duracelltomi-google-tag-manager' ),
1181
+ 'mediaeventstabtitle' => __( 'Media events', 'duracelltomi-google-tag-manager' ),
1182
+ 'depecratedeventstabtitle' => __( 'Deprecated', 'duracelltomi-google-tag-manager' ),
1183
+ 'sitetabtitle' => __( 'Site', 'duracelltomi-google-tag-manager' ),
1184
+ 'misctabtitle' => __( 'Misc', 'duracelltomi-google-tag-manager' ),
1185
+ );
1186
+ wp_localize_script( 'admin-subtabs', 'gtm4wp', $subtabtexts );
1187
+
1188
+ wp_enqueue_script( 'admin-subtabs' );
1189
+ wp_enqueue_script( 'admin-tabcreator', $gtp4wp_plugin_url . 'js/admin-tabcreator.js', array( 'jquery-core' ), GTM4WP_VERSION );
1190
+
1191
+ wp_enqueue_style( 'gtm4wp-validate', $gtp4wp_plugin_url . 'css/admin-gtm4wp.css', array(), GTM4WP_VERSION );
1192
+ }
1193
+ }
1194
+
1195
+ function gtm4wp_admin_head() {
1196
+ echo '
1197
+ <style type="text/css">
1198
+ .gtmid_validation_error,
1199
+ .goid_validation_error,
1200
+ .goid_ga_validation_error,
1201
+ .ampid_validation_error,
1202
+ .datalayername_validation_error,
1203
+ .gtmauth_validation_error,
1204
+ .gtmpreview_validation_error,
1205
+ .gtm_wpconfig_set {
1206
+ color: #c00;
1207
+ font-weight: bold;
1208
+ }
1209
+ .gtmid_validation_error,
1210
+ .goid_validation_error,
1211
+ .goid_ga_validation_error,
1212
+ .ampid_validation_error,
1213
+ .datalayername_validation_error,
1214
+ .gtmauth_validation_error,
1215
+ .gtmpreview_validation_error {
1216
+ display: none;
1217
+ }
1218
+ </style>
1219
+ <script type="text/javascript">
1220
+ jQuery(function() {
1221
+ jQuery( "#gtm4wp-options\\\\[gtm-code\\\\]" )
1222
+ .on( "blur", function() {
1223
+ var gtmid_regex = /^GTM-[A-Z0-9]+$/;
1224
+ var gtmid_list_str = jQuery( this ).val();
1225
+ if ( typeof gtmid_list_str != "string" ) {
1226
+ return;
1227
+ }
1228
+ var gtmid_list = trim( gtmid_list_str ).split( "," );
1229
+
1230
+ var gtmid_haserror = false;
1231
+ for( var i=0; i<gtmid_list.length; i++ ) {
1232
+ gtmid_haserror = gtmid_haserror || !gtmid_regex.test( gtmid_list[ i ] );
1233
+ }
1234
+
1235
+ if ( gtmid_haserror ) {
1236
+ jQuery( ".gtmid_validation_error" )
1237
+ .show();
1238
+ } else {
1239
+ jQuery( ".gtmid_validation_error" )
1240
+ .hide();
1241
+ }
1242
+ });
1243
+
1244
+ jQuery( "#gtm4wp-options\\\\[integrate-google-optimize-idlist\\\\]" )
1245
+ .on( "blur", function() {
1246
+ var goid_regex = /^(GTM|OPT)-[A-Z0-9]+$/;
1247
+ var goid_val_str = jQuery( this ).val();
1248
+ if ( typeof goid_val_str != "string" ) {
1249
+ return;
1250
+ }
1251
+ var goid_val = trim( goid_val_str );
1252
+ if ( "" == goid_val ) {
1253
+ goid_list = [];
1254
+ } else {
1255
+ var goid_list = goid_val.split( "," );
1256
+ }
1257
+
1258
+ var goid_haserror = false;
1259
+ for( var i=0; i<goid_list.length; i++ ) {
1260
+ goid_haserror = goid_haserror || !goid_regex.test( goid_list[ i ] );
1261
+ }
1262
+
1263
+ if ( goid_haserror && (goid_list.length > 0) ) {
1264
+ jQuery( ".goid_validation_error" )
1265
+ .show();
1266
+ } else {
1267
+ jQuery( ".goid_validation_error" )
1268
+ .hide();
1269
+ }
1270
+ });
1271
+
1272
+ jQuery( "#gtm4wp-options\\\\[integrate-google-optimize-gaid\\\\]" )
1273
+ .on( "blur", function() {
1274
+ var gogaid_regex = /^UA-[0-9]+-[0-9]+$/;
1275
+ var gogaid_val_str = jQuery( this ).val();
1276
+ if ( typeof gogaid_val_str != "string" ) {
1277
+ return;
1278
+ }
1279
+ var gogaid_val = trim( gogaid_val_str );
1280
+ if ( "" == gogaid_val ) {
1281
+ gogaid_list = [];
1282
+ } else {
1283
+ var gogaid_list = gogaid_val.split( "," );
1284
+ }
1285
+
1286
+ var gogaid_haserror = false;
1287
+ for( var i=0; i<gogaid_list.length; i++ ) {
1288
+ gogaid_haserror = gogaid_haserror || !gogaid_regex.test( gogaid_list[ i ] );
1289
+ }
1290
+
1291
+ if ( gogaid_haserror && (gogaid_list.length > 0) ) {
1292
+ jQuery( ".goid_ga_validation_error" )
1293
+ .show();
1294
+ } else {
1295
+ jQuery( ".goid_ga_validation_error" )
1296
+ .hide();
1297
+ }
1298
+ });
1299
+
1300
+ jQuery( "#gtm4wp-options\\\\[integrate-amp-gtm\\\\]" )
1301
+ .on( "blur", function() {
1302
+ var ampid_regex = /^GTM-[A-Z0-9]+$/;
1303
+ var ampid_val_str = jQuery( this ).val();
1304
+ if ( typeof ampid_val_str != "string" ) {
1305
+ return;
1306
+ }
1307
+ var ampid_val = trim( ampid_val_str );
1308
+ if ( "" == ampid_val ) {
1309
+ ampid_list = [];
1310
+ } else {
1311
+ var ampid_list = ampid_val.split( "," );
1312
+ }
1313
+
1314
+ var ampid_haserror = false;
1315
+ for( var i=0; i<ampid_list.length; i++ ) {
1316
+ ampid_haserror = ampid_haserror || !ampid_regex.test( gogaid_list[ i ] );
1317
+ }
1318
+
1319
+ if ( ampid_haserror && (ampid_list.length > 0) ) {
1320
+ jQuery( ".ampid_validation_error" )
1321
+ .show();
1322
+ } else {
1323
+ jQuery( ".ampid_validation_error" )
1324
+ .hide();
1325
+ }
1326
+ });
1327
+
1328
+ jQuery( "#gtm4wp-options\\\\[gtm-datalayer-variable-name\\\\]" )
1329
+ .on( "blur", function() {
1330
+ var currentval = jQuery( this ).val();
1331
+
1332
+ jQuery( ".datalayername_validation_error" )
1333
+ .hide();
1334
+
1335
+ if ( currentval != "" ) {
1336
+ // I know this is not the exact definition for a variable name but I think other kind of variable names should not be used.
1337
+ var gtmvarname_regex = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
1338
+ if ( ! gtmvarname_regex.test( currentval ) ) {
1339
+ jQuery( ".datalayername_validation_error" )
1340
+ .show();
1341
+ }
1342
+ }
1343
+ });
1344
+
1345
+ jQuery( "#gtm4wp-options\\\\[gtm-env-gtm-auth\\\\]" )
1346
+ .on( "blur", function() {
1347
+ var currentval = jQuery( this ).val();
1348
+
1349
+ jQuery( ".gtmauth_validation_error" )
1350
+ .hide();
1351
+
1352
+ if ( currentval != "" ) {
1353
+ var gtmauth_regex = /^[a-zA-Z0-9-_]+$/;
1354
+ if ( ! gtmauth_regex.test( currentval ) ) {
1355
+ jQuery( ".gtmauth_validation_error" )
1356
+ .show();
1357
+ }
1358
+ }
1359
+ });
1360
+
1361
+ jQuery( "#gtm4wp-options\\\\[gtm-env-gtm-preview\\\\]" )
1362
+ .on( "blur", function() {
1363
+ var currentval = jQuery( this ).val();
1364
+
1365
+ jQuery( ".gtmpreview_validation_error" )
1366
+ .hide();
1367
+
1368
+ if ( currentval != "" ) {
1369
+ var gtmpreview_regex = /^env-[0-9]+$/;
1370
+ if ( ! gtmpreview_regex.test( currentval ) ) {
1371
+ jQuery( ".gtmpreview_validation_error" )
1372
+ .show();
1373
+ }
1374
+ }
1375
+ });
1376
+
1377
+ jQuery( document )
1378
+ .on( "click", ".gtm4wp-notice .notice-dismiss", function( e ) {
1379
+ jQuery.post(ajaxurl, {
1380
+ action: "gtm4wp_dismiss_notice",
1381
+ noticeid: jQuery( this ).closest(".gtm4wp-notice")
1382
+ .attr( "data-href" )
1383
+ .substring( 1 )
1384
+ });
1385
+ });
1386
+ });
1387
+ </script>';
1388
+ }
1389
+
1390
+ function gtm4wp_show_warning() {
1391
+ global $gtm4wp_options, $gtp4wp_plugin_url, $gtm4wp_integratefieldtexts, $current_user,
1392
+ $gtm4wp_def_user_notices_dismisses;
1393
+
1394
+ $woo_plugin_active = is_plugin_active( $gtm4wp_integratefieldtexts[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ]['plugintocheck'] );
1395
+ if ( $woo_plugin_active && function_exists( 'WC' ) ) {
1396
+ $woo = WC();
1397
+ } else {
1398
+ $woo = null;
1399
+ }
1400
+
1401
+ $gtm4wp_user_notices_dismisses = get_user_meta( $current_user->ID, GTM4WP_USER_NOTICES_KEY, true );
1402
+ if ( $gtm4wp_user_notices_dismisses === '' ) {
1403
+ if ( is_array( $gtm4wp_def_user_notices_dismisses ) ) {
1404
+ $gtm4wp_user_notices_dismisses = $gtm4wp_def_user_notices_dismisses;
1405
+ } else {
1406
+ $gtm4wp_user_notices_dismisses = array();
1407
+ }
1408
+ } else {
1409
+ $gtm4wp_user_notices_dismisses = @unserialize( $gtm4wp_user_notices_dismisses );
1410
+ if ( false === $gtm4wp_user_notices_dismisses || !is_array( $gtm4wp_user_notices_dismisses ) ) {
1411
+ $gtm4wp_user_notices_dismisses = array();
1412
+ }
1413
+ }
1414
+ $gtm4wp_user_notices_dismisses = array_merge( $gtm4wp_def_user_notices_dismisses, $gtm4wp_user_notices_dismisses );
1415
+
1416
+ if ( ( trim( $gtm4wp_options[ GTM4WP_OPTION_GTM_CODE ] ) == '' ) && ( false === $gtm4wp_user_notices_dismisses['enter-gtm-code'] ) ) {
1417
+ echo '<div class="gtm4wp-notice notice notice-error is-dismissible" data-href="?enter-gtm-code"><p><strong>' . sprintf( __( 'To start using Google Tag Manager for WordPress, please <a href="%s">enter your GTM ID</a>', 'duracelltomi-google-tag-manager' ), 'options-general.php?page=' . GTM4WP_ADMINSLUG ) . '</strong></p></div>';
1418
+ }
1419
+
1420
+ if ( (
1421
+ ( '' != $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_AUTH ] ) && ( '' == $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_PREVIEW ] )
1422
+ ) || (
1423
+ ( '' == $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_AUTH ] ) && ( '' != $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_PREVIEW ] )
1424
+ ) ) {
1425
+ echo '<div class="gtm4wp-notice notice notice-error" data-href="?incomplete-gtm-env-config"><p><strong>' . sprintf( __( 'Incomplete Google Tag Manager environment configuration: either gtm_preview or gtm_auth parameter value is missing!', 'duracelltomi-google-tag-manager' ), 'options-general.php?page=' . GTM4WP_ADMINSLUG ) . '</strong></p></div>';
1426
+ }
1427
+
1428
+ if ( ( false === $gtm4wp_user_notices_dismisses['wc-ga-plugin-warning'] ) || ( false === $gtm4wp_user_notices_dismisses['wc-gayoast-plugin-warning'] ) ) {
1429
+ $is_wc_active = $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKCLASSICEC ] ||
1430
+ $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ||
1431
+ $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ];
1432
+
1433
+ if ( ( false === $gtm4wp_user_notices_dismisses['wc-ga-plugin-warning'] ) && $is_wc_active && is_plugin_active( 'woocommerce-google-analytics-integration/woocommerce-google-analytics-integration.php' ) ) {
1434
+ echo '<div class="gtm4wp-notice notice notice-warning is-dismissible" data-href="?wc-ga-plugin-warning"><p><strong>' . __( 'Notice: you should deactivate the plugin "WooCommerce Google Analytics Integration" if you are using Google Analytics tags inside Google Tag Manager!', 'duracelltomi-google-tag-manager' ) . '</strong></p></div>';
1435
+ }
1436
+
1437
+ if ( ( false === $gtm4wp_user_notices_dismisses['wc-gayoast-plugin-warning'] ) && $is_wc_active && is_plugin_active( 'google-analytics-for-wordpress/googleanalytics.php' ) ) {
1438
+ echo '<div class="gtm4wp-notice notice notice-warning is-dismissible" data-href="?wc-gayoast-plugin-warning"><p><strong>' . __( 'Notice: you should deactivate the plugin "Google Analytics for WordPress by MonsterInsights" if you are using Google Analytics tags inside Google Tag Manager!', 'duracelltomi-google-tag-manager' ) . '</strong></p></div>';
1439
+ }
1440
+ }
1441
+
1442
+ if ( ( false === $gtm4wp_user_notices_dismisses['php72-warning'] ) && ( version_compare( PHP_VERSION, '7.2.0' ) < 0 ) ) {
1443
+ echo '<div class="gtm4wp-notice notice notice-warning is-dismissible" data-href="?php72-warning"><p><strong>' . __( 'Warning: You are using an outdated version of PHP (v' . PHP_VERSION . ') that might be not compatible with future versions of the plugin Google Tag Manager for WordPress (GTM4WP). Please consider to upgrade your PHP.', 'duracelltomi-google-tag-manager' ) . '</strong></p></div>';
1444
+ }
1445
+ }
1446
+
1447
+ function gtm4wp_dismiss_notice() {
1448
+ global $gtm4wp_def_user_notices_dismisses, $current_user;
1449
+
1450
+ $gtm4wp_user_notices_dismisses = get_user_meta( $current_user->ID, GTM4WP_USER_NOTICES_KEY, true );
1451
+ if ( $gtm4wp_user_notices_dismisses === '' ) {
1452
+ if ( is_array( $gtm4wp_def_user_notices_dismisses ) ) {
1453
+ $gtm4wp_user_notices_dismisses = $gtm4wp_def_user_notices_dismisses;
1454
+ } else {
1455
+ $gtm4wp_user_notices_dismisses = array();
1456
+ }
1457
+ } else {
1458
+ $gtm4wp_user_notices_dismisses = @unserialize( $gtm4wp_user_notices_dismisses );
1459
+ if ( false === $gtm4wp_user_notices_dismisses || !is_array( $gtm4wp_user_notices_dismisses ) ) {
1460
+ $gtm4wp_user_notices_dismisses = array();
1461
+ }
1462
+ }
1463
+ $gtm4wp_user_notices_dismisses = array_merge( $gtm4wp_def_user_notices_dismisses, $gtm4wp_user_notices_dismisses );
1464
+
1465
+ $noticeid = trim( basename( $_POST['noticeid'] ) );
1466
+ if ( array_key_exists( $noticeid, $gtm4wp_user_notices_dismisses ) ) {
1467
+ $gtm4wp_user_notices_dismisses[ $noticeid ] = true;
1468
+ update_user_meta( $current_user->ID, GTM4WP_USER_NOTICES_KEY, serialize( $gtm4wp_user_notices_dismisses ) );
1469
+ }
1470
+ }
1471
+
1472
+ function gtm4wp_add_plugin_action_links( $links, $file ) {
1473
+ global $gtp4wp_plugin_basename;
1474
+
1475
+ if ( $file != $gtp4wp_plugin_basename ) {
1476
+ return $links;
1477
+ }
1478
+
1479
+ $settings_link = '<a href="' . menu_page_url( GTM4WP_ADMINSLUG, false ) . '">' . esc_html( __( 'Settings' ) ) . '</a>';
1480
+
1481
+ array_unshift( $links, $settings_link );
1482
+
1483
+ return $links;
1484
+ }
1485
+
1486
+ function gtm4wp_show_upgrade_notification( $current_plugin_metadata, $new_plugin_metadata ) {
1487
+ if ( isset( $new_plugin_metadata->upgrade_notice ) && strlen( trim( $new_plugin_metadata->upgrade_notice ) ) > 0 ) {
1488
+ echo '<p style="background-color: #d54e21; padding: 10px; color: #f9f9f9; margin-top: 10px"><strong>Important Upgrade Notice:</strong> ';
1489
+ echo esc_html( $new_plugin_metadata->upgrade_notice ), '</p>';
1490
+ }
1491
+ }
1492
+
1493
+ add_action( 'admin_init', 'gtm4wp_admin_init' );
1494
+ add_action( 'admin_menu', 'gtm4wp_add_admin_page' );
1495
+ add_action( 'admin_enqueue_scripts', 'gtm4wp_add_admin_js' );
1496
+ add_action( 'admin_notices', 'gtm4wp_show_warning' );
1497
+ add_action( 'admin_head', 'gtm4wp_admin_head' );
1498
+ add_filter( 'plugin_action_links', 'gtm4wp_add_plugin_action_links', 10, 2 );
1499
+ add_action( 'wp_ajax_gtm4wp_dismiss_notice', 'gtm4wp_dismiss_notice' );
1500
+ add_action( 'in_plugin_update_message-duracelltomi-google-tag-manager-for-wordpress/duracelltomi-google-tag-manager-for-wordpress.php', 'gtm4wp_show_upgrade_notification', 10, 2 );
duracelltomi-google-tag-manager-for-wordpress.php CHANGED
@@ -1,7 +1,7 @@
1
  <?php
2
  /*
3
  Plugin Name: Google Tag Manager for Wordpress
4
- Version: 1.13.1
5
  Plugin URI: https://gtm4wp.com/
6
  Description: The first Google Tag Manager plugin for WordPress with business goals in mind
7
  Author: Thomas Geiger
@@ -13,7 +13,7 @@ WC requires at least: 3.2
13
  WC tested up to: 5.3.0
14
  */
15
 
16
- define( 'GTM4WP_VERSION', '1.13.1' );
17
  define( 'GTM4WP_PATH', plugin_dir_path( __FILE__ ) );
18
 
19
  global $gtp4wp_plugin_url, $gtp4wp_plugin_basename;
1
  <?php
2
  /*
3
  Plugin Name: Google Tag Manager for Wordpress
4
+ Version: 1.14
5
  Plugin URI: https://gtm4wp.com/
6
  Description: The first Google Tag Manager plugin for WordPress with business goals in mind
7
  Author: Thomas Geiger
13
  WC tested up to: 5.3.0
14
  */
15
 
16
+ define( 'GTM4WP_VERSION', '1.14' );
17
  define( 'GTM4WP_PATH', plugin_dir_path( __FILE__ ) );
18
 
19
  global $gtp4wp_plugin_url, $gtp4wp_plugin_basename;
integration/google-optimize.php CHANGED
@@ -1,64 +1,64 @@
1
- <?php
2
- function gtm4wp_go_pagehiding_snippet() {
3
- global $gtm4wp_options;
4
-
5
- $gtm4wp_goids = explode( ',', $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_GOOGLEOPTIMIZEIDS ] );
6
- $gtm4wp_goid_pagehiding_list = array();
7
- if ( count( $gtm4wp_goids ) > 0 ) {
8
- foreach ( $gtm4wp_goids as $gtm4wp_onegoid ) {
9
- $gtm4wp_goid_pagehiding_list[] = "'" . $gtm4wp_onegoid . "': true";
10
- }
11
-
12
- $gtm4wp_gotimeout = (int) $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_GOOGLEOPTIMIZETIMEOUT ];
13
- if ( 0 == $gtm4wp_gotimeout ) {
14
- $gtm4wp_gotimeout = 4000;
15
- }
16
-
17
- echo "
18
- <!-- GTM4WP: Google Optimize Anti-flicker snippet -->
19
- <style>
20
- .async-hide {
21
- opacity: 0 !important
22
- }
23
- </style>
24
- <script>
25
- (function(a,s,y,n,c,h,i,d,e) {
26
- s.className+=' '+y;
27
- h.start=1*new Date;
28
- h.end=i=function() {
29
- s.className=s.className.replace(RegExp(' ?'+y),'')
30
- };
31
- (a[n]=a[n]||[]).hide=h;
32
- setTimeout(function() {
33
- i();
34
- h.end=null
35
- },c);
36
- h.timeout=c;
37
- })(window,document.documentElement,'async-hide','dataLayer'," . $gtm4wp_gotimeout . ",{" . implode( ", ", $gtm4wp_goid_pagehiding_list ) . "});
38
- </script>
39
- <!-- GTM4WP: End of Google Optimize Page Hiding snippet -->";
40
- }
41
- }
42
-
43
- function gtm4wp_go_snippet( $content ) {
44
- global $gtm4wp_options;
45
-
46
- $gtm4wp_goids = explode( ',', $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_GOOGLEOPTIMIZEIDS ] );
47
- $gtm4wp_goid_list = array();
48
- if ( count( $gtm4wp_goids ) > 0 ) {
49
- foreach ( $gtm4wp_goids as $gtm4wp_onegoid ) {
50
- $gtm4wp_goid_list[] = '
51
- <script src="https://www.googleoptimize.com/optimize.js?id=' . $gtm4wp_onegoid . '" onerror="dataLayer.hide.end && dataLayer.hide.end()"></script>';
52
- }
53
-
54
- $content .= "
55
- <!-- GTM4WP: Load Google Optimize containers -->
56
- " . implode("", $gtm4wp_goid_list) . "
57
- <!-- GTM4WP: End of Load Google Optimize containers -->";
58
- }
59
-
60
- return $content;
61
- }
62
-
63
- add_action( 'wp_head', 'gtm4wp_go_pagehiding_snippet', 1 );
64
- add_filter( GTM4WP_WPFILTER_AFTER_DATALAYER, 'gtm4wp_go_snippet' );
1
+ <?php
2
+ function gtm4wp_go_pagehiding_snippet() {
3
+ global $gtm4wp_options;
4
+
5
+ $gtm4wp_goids = explode( ',', $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_GOOGLEOPTIMIZEIDS ] );
6
+ $gtm4wp_goid_pagehiding_list = array();
7
+ if ( count( $gtm4wp_goids ) > 0 ) {
8
+ foreach ( $gtm4wp_goids as $gtm4wp_onegoid ) {
9
+ $gtm4wp_goid_pagehiding_list[] = "'" . $gtm4wp_onegoid . "': true";
10
+ }
11
+
12
+ $gtm4wp_gotimeout = (int) $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_GOOGLEOPTIMIZETIMEOUT ];
13
+ if ( 0 == $gtm4wp_gotimeout ) {
14
+ $gtm4wp_gotimeout = 4000;
15
+ }
16
+
17
+ echo "
18
+ <!-- GTM4WP: Google Optimize Anti-flicker snippet -->
19
+ <style>
20
+ .async-hide {
21
+ opacity: 0 !important
22
+ }
23
+ </style>
24
+ <script>
25
+ (function(a,s,y,n,c,h,i,d,e) {
26
+ s.className+=' '+y;
27
+ h.start=1*new Date;
28
+ h.end=i=function() {
29
+ s.className=s.className.replace(RegExp(' ?'+y),'')
30
+ };
31
+ (a[n]=a[n]||[]).hide=h;
32
+ setTimeout(function() {
33
+ i();
34
+ h.end=null
35
+ },c);
36
+ h.timeout=c;
37
+ })(window,document.documentElement,'async-hide','dataLayer'," . $gtm4wp_gotimeout . ",{" . implode( ", ", $gtm4wp_goid_pagehiding_list ) . "});
38
+ </script>
39
+ <!-- GTM4WP: End of Google Optimize Page Hiding snippet -->";
40
+ }
41
+ }
42
+
43
+ function gtm4wp_go_snippet( $content ) {
44
+ global $gtm4wp_options;
45
+
46
+ $gtm4wp_goids = explode( ',', $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_GOOGLEOPTIMIZEIDS ] );
47
+ $gtm4wp_goid_list = array();
48
+ if ( count( $gtm4wp_goids ) > 0 ) {
49
+ foreach ( $gtm4wp_goids as $gtm4wp_onegoid ) {
50
+ $gtm4wp_goid_list[] = '
51
+ <script src="https://www.googleoptimize.com/optimize.js?id=' . $gtm4wp_onegoid . '" onerror="dataLayer.hide.end && dataLayer.hide.end()"></script>';
52
+ }
53
+
54
+ $content .= "
55
+ <!-- GTM4WP: Load Google Optimize containers -->
56
+ " . implode("", $gtm4wp_goid_list) . "
57
+ <!-- GTM4WP: End of Load Google Optimize containers -->";
58
+ }
59
+
60
+ return $content;
61
+ }
62
+
63
+ add_action( 'wp_head', 'gtm4wp_go_pagehiding_snippet', 1 );
64
+ add_filter( GTM4WP_WPFILTER_AFTER_DATALAYER, 'gtm4wp_go_snippet' );
integration/soundcloud.php CHANGED
@@ -1,6 +1,6 @@
1
- <?php
2
- if ( ! is_admin() ) {
3
- $in_footer = apply_filters( 'gtm4wp_soundcloud', false );
4
- wp_enqueue_script( 'gtm4wp-soundcloud-api', 'https://w.soundcloud.com/player/api.js', array(), '1.0', $in_footer );
5
- wp_enqueue_script( 'gtm4wp-soundcloud', $gtp4wp_plugin_url . 'js/gtm4wp-soundcloud.js', array( 'jquery' ), GTM4WP_VERSION, $in_footer );
6
- }
1
+ <?php
2
+ if ( ! is_admin() ) {
3
+ $in_footer = apply_filters( 'gtm4wp_soundcloud', true );
4
+ wp_enqueue_script( 'gtm4wp-soundcloud-api', 'https://w.soundcloud.com/player/api.js', array(), '1.0', $in_footer );
5
+ wp_enqueue_script( 'gtm4wp-soundcloud', $gtp4wp_plugin_url . 'js/gtm4wp-soundcloud.js', array(), GTM4WP_VERSION, $in_footer );
6
+ }
integration/vimeo.php CHANGED
@@ -1,7 +1,7 @@
1
- <?php
2
- if ( ! is_admin() ) {
3
- $in_footer = apply_filters( 'gtm4wp_vimeo', false );
4
- // wp_enqueue_script( "gtm4wp-vimeo-froogaloop", $gtp4wp_plugin_url . "js/froogaloop.js", array(), "2.0", $in_footer );
5
- wp_enqueue_script( 'gtm4wp-vimeo-api', 'https://player.vimeo.com/api/player.js', array(), '1.0', $in_footer );
6
- wp_enqueue_script( 'gtm4wp-vimeo', $gtp4wp_plugin_url . 'js/gtm4wp-vimeo.js', array( 'jquery' ), GTM4WP_VERSION, $in_footer );
7
- }
1
+ <?php
2
+ if ( ! is_admin() ) {
3
+ $in_footer = apply_filters( 'gtm4wp_vimeo', true );
4
+
5
+ wp_enqueue_script( 'gtm4wp-vimeo-api', 'https://player.vimeo.com/api/player.js', array(), '1.0', $in_footer );
6
+ wp_enqueue_script( 'gtm4wp-vimeo', $gtp4wp_plugin_url . 'js/gtm4wp-vimeo.js', array(), GTM4WP_VERSION, $in_footer );
7
+ }
integration/woocommerce.php CHANGED
@@ -1,1149 +1,1297 @@
1
- <?php
2
- define( 'GTM4WP_WPFILTER_EEC_PRODUCT_ARRAY', 'gtm4wp_eec_product_array' );
3
- define( 'GTM4WP_WPFILTER_EEC_CART_ITEM', 'gtm4wp_eec_cart_item' );
4
- define( 'GTM4WP_WPFILTER_EEC_ORDER_ITEM', 'gtm4wp_eec_order_item' );
5
-
6
- $gtm4wp_product_counter = 0;
7
- $gtm4wp_last_widget_title = 'Sidebar Products';
8
- if ( function_exists( 'WC' ) ) {
9
- $GLOBALS['gtm4wp_is_woocommerce3_7'] = version_compare( WC()->version, '3.7', '>=' );
10
- } else {
11
- $GLOBALS['gtm4wp_is_woocommerce3_7'] = false;
12
- }
13
- $GLOBALS['gtm4wp_grouped_product_ix'] = 1;
14
-
15
- // from https://snippets.webaware.com.au/ramblings/php-really-doesnt-unicode/
16
- function gtm4wp_untexturize( $fancy ) {
17
- $fixes = false;
18
-
19
- if ( $fixes === false ) {
20
- $fixes = array(
21
- json_decode( '"\u201C"' ) => '"', // left double quotation mark
22
- json_decode( '"\u201D"' ) => '"', // right double quotation mark
23
- json_decode( '"\u2018"' ) => "'", // left single quotation mark
24
- json_decode( '"\u2019"' ) => "'", // right single quotation mark
25
- json_decode( '"\u2032"' ) => "'", // prime (minutes, feet)
26
- json_decode( '"\u2033"' ) => '"', // double prime (seconds, inches)
27
- json_decode( '"\u2013"' ) => '-', // en dash
28
- json_decode( '"\u2014"' ) => '--', // em dash
29
- );
30
- }
31
-
32
- $normal = strtr( $fancy, $fixes );
33
-
34
- return $normal;
35
- }
36
-
37
- function gtm4wp_woocommerce_html_entity_decode( $val ) {
38
- return gtm4wp_untexturize( html_entity_decode( $val, ENT_QUOTES, 'utf-8' ) );
39
- }
40
-
41
- function gtm4wp_prefix_productid( $product_id ) {
42
- global $gtm4wp_options;
43
-
44
- if ( '' != $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMPRODIDPREFIX ] ) {
45
- return $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMPRODIDPREFIX ] . $product_id;
46
- } else {
47
- return $product_id;
48
- }
49
- }
50
-
51
- // from https://stackoverflow.com/questions/1252693/using-str-replace-so-that-it-only-acts-on-the-first-match
52
- function gtm4wp_str_replace_first( $from, $to, $subject ) {
53
- $from = '/' . preg_quote( $from, '/' ) . '/';
54
-
55
- return preg_replace( $from, $to, $subject, 1 );
56
- }
57
-
58
- function gtm4wp_get_product_category_hierarchy( $category_id ) {
59
- $cat_hierarchy = '';
60
-
61
- $category_parent_list = get_term_parents_list(
62
- $category_id,
63
- 'product_cat',
64
- array(
65
- 'format' => 'name',
66
- 'separator' => '/',
67
- 'link' => false,
68
- 'inclusive' => true,
69
- )
70
- );
71
-
72
- if ( is_string( $category_parent_list ) ) {
73
- $cat_hierarchy = trim( $category_parent_list, '/' );
74
- }
75
-
76
- return $cat_hierarchy;
77
- }
78
-
79
- function gtm4wp_get_product_category( $product_id, $fullpath = false ) {
80
- $product_cat = '';
81
-
82
- $_product_cats = get_the_terms( $product_id, 'product_cat' );
83
- if ( ( is_array( $_product_cats ) ) && ( count( $_product_cats ) > 0 ) ) {
84
- $first_product_cat = array_pop( $_product_cats );
85
- if ( $fullpath ) {
86
- $product_cat = gtm4wp_get_product_category_hierarchy( $first_product_cat->term_id );
87
- } else {
88
- $product_cat = $first_product_cat->name;
89
- }
90
- }
91
-
92
- return $product_cat;
93
- }
94
-
95
- function gtm4wp_woocommerce_getproductterm( $product_id, $taxonomy ) {
96
- $gtm4wp_product_terms = get_the_terms( $product_id, $taxonomy );
97
- if ( is_array( $gtm4wp_product_terms ) && ( count( $gtm4wp_product_terms ) > 0 ) ) {
98
- return $gtm4wp_product_terms[0]->name;
99
- }
100
-
101
- return "";
102
- }
103
-
104
- function gtm4wp_process_product( $product, $additional_product_attributes, $attributes_used_for ) {
105
- global $gtm4wp_options;
106
-
107
- if ( ! $product ) {
108
- return false;
109
- }
110
-
111
- if ( ! ( $product instanceof WC_Product ) ) {
112
- return false;
113
- }
114
-
115
- $product_id = $product->get_id();
116
- $product_type = $product->get_type();
117
- $remarketing_id = $product_id;
118
- $product_sku = $product->get_sku();
119
-
120
- if ( 'variation' == $product_type ) {
121
- $parent_product_id = $product->get_parent_id();
122
- $product_cat = gtm4wp_get_product_category( $parent_product_id, $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCUSEFULLCATEGORYPATH ] );
123
- } else {
124
- $product_cat = gtm4wp_get_product_category( $product_id, $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCUSEFULLCATEGORYPATH ] );
125
- }
126
-
127
- if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCUSESKU ] && ( '' != $product_sku ) ) {
128
- $remarketing_id = $product_sku;
129
- }
130
-
131
- $_temp_productdata = array(
132
- 'id' => $remarketing_id,
133
- 'name' => $product->get_title(),
134
- 'sku' => $product_sku ? $product_sku : $product_id,
135
- 'category' => $product_cat,
136
- 'price' => round( (float) wc_get_price_to_display( $product ), 2),
137
- 'stocklevel' => $product->get_stock_quantity()
138
- );
139
-
140
- if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEECBRANDTAXONOMY ] != "" ) {
141
- if ( isset( $parent_product_id ) && ( $parent_product_id !== 0 ) ) {
142
- $product_id_to_query = $parent_product_id;
143
- } else {
144
- $product_id_to_query = $product_id;
145
- }
146
-
147
- $_temp_productdata[ "brand" ] = gtm4wp_woocommerce_getproductterm( $product_id_to_query, $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEECBRANDTAXONOMY ] );
148
- }
149
-
150
- if ( 'variation' == $product_type ) {
151
- $_temp_productdata['variant'] = implode( ',', $product->get_variation_attributes() );
152
- }
153
-
154
- $_temp_productdata = array_merge( $_temp_productdata, $additional_product_attributes );
155
-
156
- return apply_filters( GTM4WP_WPFILTER_EEC_PRODUCT_ARRAY, $_temp_productdata, $attributes_used_for );
157
- }
158
-
159
- function gtm4wp_get_gads_product_id_variable_name( $vertical_id ) {
160
- global $gtm4wp_business_verticals_ids;
161
-
162
- if ( array_key_exists( $vertical_id, $gtm4wp_business_verticals_ids ) ) {
163
- return $gtm4wp_business_verticals_ids[ $vertical_id ];
164
- } else {
165
- return "id";
166
- }
167
- }
168
-
169
- function gtm4wp_map_eec_to_ga4( $productdata ) {
170
- global $gtm4wp_options;
171
-
172
- if ( !is_array($productdata) ) {
173
- return;
174
- }
175
-
176
- $category_path = array_key_exists( "category", $productdata ) ? $productdata[ "category" ] : "";
177
- $category_parts = explode('/', $category_path);
178
-
179
- // default, required parameters
180
- $ga4_product = array(
181
- 'item_id' => array_key_exists( "id", $productdata ) ? $productdata[ "id" ] : "",
182
- 'item_name' => array_key_exists( "name", $productdata ) ? $productdata[ "name" ] : "",
183
- 'item_brand' => array_key_exists( "brand", $productdata ) ? $productdata[ "brand" ] : "",
184
- 'price' => array_key_exists( "price", $productdata ) ? $productdata[ "price" ] : ""
185
- );
186
-
187
- // category, also handle category path
188
- if ( 1 == count($category_parts) ) {
189
- $ga4_product[ "item_category" ] = $category_parts[0];
190
- } else if ( count($category_parts) > 1 ) {
191
- $ga4_product[ "item_category" ] = $category_parts[0];
192
- for( $i=1; $i < min( 5, count( $category_parts ) ); $i++ ) {
193
- $ga4_product[ "item_category_" . (string)($i+1) ] = $category_parts[$i];
194
- }
195
- }
196
-
197
- // optional parameters which should not be included in the array if not set
198
- if ( array_key_exists( "variant", $productdata ) ) {
199
- $ga4_product[ "item_variant" ] = $productdata[ "variant" ];
200
- }
201
- if ( array_key_exists( "listname", $productdata ) ) {
202
- $ga4_product[ "item_list_name" ] = $productdata[ "listname" ];
203
- }
204
- if ( array_key_exists( "listposition", $productdata ) ) {
205
- $ga4_product[ "index" ] = $productdata[ "listposition" ];
206
- }
207
- if ( array_key_exists( "quantity", $productdata ) ) {
208
- $ga4_product[ "quantity" ] = $productdata[ "quantity" ];
209
- }
210
- if ( array_key_exists( "coupon", $productdata ) ) {
211
- $ga4_product[ "coupon" ] = $productdata[ "coupon" ];
212
- }
213
-
214
- $ga4_product[ "google_business_vertical" ] = $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCBUSINESSVERTICAL ];
215
- $ga4_product[ gtm4wp_get_gads_product_id_variable_name( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCBUSINESSVERTICAL ] ) ] = gtm4wp_prefix_productid( $ga4_product["item_id"] );
216
-
217
- return $ga4_product;
218
- }
219
-
220
- function gtm4wp_process_order_items( $order ) {
221
- global $gtm4wp_options;
222
-
223
- $return_data = array(
224
- 'products' => [],
225
- 'sumprice' => 0,
226
- 'product_ids' => []
227
- );
228
-
229
- if ( ! $order ) {
230
- return $return_data;
231
- }
232
-
233
- $order_items = $order->get_items();
234
-
235
- if ( $order_items ) {
236
- foreach ( $order_items as $item ) {
237
- if ( ! apply_filters( GTM4WP_WPFILTER_EEC_ORDER_ITEM, true, $item ) ) {
238
- continue;
239
- }
240
-
241
- $product = $item->get_product();
242
- $inc_tax = ( 'incl' === get_option( 'woocommerce_tax_display_shop' ) );
243
- $product_price = round( (float) $order->get_item_total( $item, $inc_tax ), 2);
244
- $eec_product_array = gtm4wp_process_product( $product, array(
245
- 'quantity' => $item->get_quantity(),
246
- 'price' => $product_price
247
- ), 'purchase' );
248
-
249
- if ( $eec_product_array ) {
250
- $return_data['products'][] = $eec_product_array;
251
- $return_data['sumprice'] += $product_price * $eec_product_array['quantity'];
252
- $return_data['product_ids'][] = gtm4wp_prefix_productid( $eec_product_array['id'] );
253
- }
254
- }
255
- }
256
-
257
- return $return_data;
258
- }
259
-
260
- function gtm4wp_woocommerce_addglobalvars( $return = '' ) {
261
- global $gtm4wp_options;
262
-
263
- if ( function_exists( 'WC' ) && WC()->cart ) {
264
- $gtm4wp_needs_shipping_address = (bool) WC()->cart->needs_shipping_address();
265
- } else {
266
- $gtm4wp_needs_shipping_address = false;
267
- }
268
-
269
- $return .= '
270
- var gtm4wp_use_sku_instead = ' . (int) ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCUSESKU ] ) . ';
271
- var gtm4wp_id_prefix = \'' . esc_js( gtm4wp_prefix_productid( '' ) ) . '\';
272
- var gtm4wp_remarketing = ' . gtm4wp_escjs_boolean( (bool) ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ] ) ) . ';
273
- var gtm4wp_eec = ' . gtm4wp_escjs_boolean( (bool) ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) ) . ';
274
- var gtm4wp_classicec = ' . gtm4wp_escjs_boolean( (bool) ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKCLASSICEC ] ) ) . ';
275
- var gtm4wp_currency = \'' . esc_js( get_woocommerce_currency() ) . '\';
276
- var gtm4wp_product_per_impression = ' . (int) ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCPRODPERIMPRESSION ] ) . ';
277
- var gtm4wp_needs_shipping_address = ' . gtm4wp_escjs_boolean( $gtm4wp_needs_shipping_address ) . ';
278
- var gtm4wp_business_vertical = \'' . esc_js( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCBUSINESSVERTICAL ] ) . '\';
279
- var gtm4wp_business_vertical_id = \'' . gtm4wp_get_gads_product_id_variable_name( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCBUSINESSVERTICAL ] ) . '\';';
280
-
281
- return $return;
282
- }
283
-
284
- function gtm4wp_woocommerce_datalayer_filter_items( $dataLayer ) {
285
- global $gtm4wp_options, $wp_query, $gtm4wp_datalayer_name, $gtm4wp_product_counter, $gtm4wp_is_woocommerce3_7;
286
-
287
- $woo = WC();
288
-
289
- if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCCUSTOMERDATA ] ) {
290
- if ( $woo->customer instanceof WC_Customer ) {
291
- // 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
292
- $woo_customer = new WC_Customer( $woo->customer->get_id() );
293
-
294
- $dataLayer['customerTotalOrders'] = $woo_customer->get_order_count();
295
- $dataLayer['customerTotalOrderValue'] = $woo_customer->get_total_spent();
296
-
297
- $dataLayer['customerFirstName'] = $woo_customer->get_first_name();
298
- $dataLayer['customerLastName'] = $woo_customer->get_last_name();
299
-
300
- $dataLayer['customerBillingFirstName'] = $woo_customer->get_billing_first_name();
301
- $dataLayer['customerBillingLastName'] = $woo_customer->get_billing_last_name();
302
- $dataLayer['customerBillingCompany'] = $woo_customer->get_billing_company();
303
- $dataLayer['customerBillingAddress1'] = $woo_customer->get_billing_address_1();
304
- $dataLayer['customerBillingAddress2'] = $woo_customer->get_billing_address_2();
305
- $dataLayer['customerBillingCity'] = $woo_customer->get_billing_city();
306
- $dataLayer['customerBillingPostcode'] = $woo_customer->get_billing_postcode();
307
- $dataLayer['customerBillingCountry'] = $woo_customer->get_billing_country();
308
- $dataLayer['customerBillingEmail'] = $woo_customer->get_billing_email();
309
- $dataLayer['customerBillingPhone'] = $woo_customer->get_billing_phone();
310
-
311
- $dataLayer['customerShippingFirstName'] = $woo_customer->get_shipping_first_name();
312
- $dataLayer['customerShippingLastName'] = $woo_customer->get_shipping_last_name();
313
- $dataLayer['customerShippingCompany'] = $woo_customer->get_shipping_company();
314
- $dataLayer['customerShippingAddress1'] = $woo_customer->get_shipping_address_1();
315
- $dataLayer['customerShippingAddress2'] = $woo_customer->get_shipping_address_2();
316
- $dataLayer['customerShippingCity'] = $woo_customer->get_shipping_city();
317
- $dataLayer['customerShippingPostcode'] = $woo_customer->get_shipping_postcode();
318
- $dataLayer['customerShippingCountry'] = $woo_customer->get_shipping_country();
319
- }
320
- }
321
-
322
- if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEINCLUDECARTINDL ] && version_compare( $woo->version, "3.2", ">=" ) && isset($woo) && isset($woo->cart) ) {
323
- $current_cart = $woo->cart;
324
- $dataLayer["cartContent"] = array(
325
- "totals" => array(
326
- "applied_coupons" => $current_cart->get_applied_coupons(),
327
- "discount_total" => $current_cart->get_discount_total(),
328
- "subtotal" => $current_cart->get_subtotal(),
329
- "total" => $current_cart->get_cart_contents_total()
330
- ),
331
- "items" => array()
332
- );
333
-
334
- foreach( $current_cart->get_cart() as $cart_item_id => $cart_item_data) {
335
- $product = apply_filters( 'woocommerce_cart_item_product', $cart_item_data["data"], $cart_item_data, $cart_item_id );
336
- if (
337
- !apply_filters( GTM4WP_WPFILTER_EEC_CART_ITEM, true, $cart_item_data )
338
- || !apply_filters( 'woocommerce_widget_cart_item_visible', true, $cart_item_data, $cart_item_id )
339
- ) {
340
- continue;
341
- }
342
-
343
- $eec_product_array = gtm4wp_process_product( $product, array(
344
- 'quantity' => $cart_item_data["quantity"]
345
- ), 'cart' );
346
-
347
- $dataLayer["cartContent"]["items"][] = $eec_product_array;
348
- }
349
- }
350
-
351
- if ( is_product_category() || is_product_tag() || is_front_page() || is_shop() ) {
352
- $ecomm_pagetype = 'category';
353
- if ( is_front_page() ) {
354
- $ecomm_pagetype = 'home';
355
- } elseif ( is_search() ) {
356
- $ecomm_pagetype = 'searchresults';
357
- }
358
-
359
- if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ] ) {
360
- $dataLayer['ecomm_prodid'] = array();
361
- $dataLayer['ecomm_pagetype'] = $ecomm_pagetype;
362
- $dataLayer['ecomm_totalvalue'] = 0;
363
- }
364
- } elseif ( is_product() ) {
365
- if (
366
- $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ]
367
- || ( true === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] )
368
- ) {
369
- $postid = get_the_ID();
370
- $product = wc_get_product( $postid );
371
-
372
- $eec_product_array = gtm4wp_process_product( $product, array(), 'productdetail' );
373
-
374
- $dataLayer['productRatingCounts'] = $product->get_rating_counts();
375
- $dataLayer['productAverageRating'] = (float) $product->get_average_rating();
376
- $dataLayer['productReviewCount'] = (int) $product->get_review_count();
377
- $dataLayer['productType'] = $product->get_type();
378
-
379
- switch ( $dataLayer['productType'] ) {
380
- case 'variable': {
381
- $dataLayer['productIsVariable'] = 1;
382
-
383
- $dataLayer['ecomm_prodid'] = gtm4wp_prefix_productid( $eec_product_array[ 'id' ] );
384
- $dataLayer['ecomm_pagetype'] = 'product';
385
- $dataLayer['ecomm_totalvalue'] = $eec_product_array[ 'price' ];
386
-
387
- break;
388
- }
389
-
390
- case 'grouped': {
391
- $dataLayer['productIsVariable'] = 0;
392
-
393
- break;
394
- }
395
-
396
- default: {
397
- $dataLayer['productIsVariable'] = 0;
398
-
399
- if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ] ) {
400
- $dataLayer['ecomm_prodid'] = gtm4wp_prefix_productid( $eec_product_array[ 'id' ] );
401
- $dataLayer['ecomm_pagetype'] = 'product';
402
- $dataLayer['ecomm_totalvalue'] = $eec_product_array['price'];
403
- }
404
-
405
- if ( true === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) {
406
- $currencyCode = get_woocommerce_currency();
407
-
408
- $dataLayer['event'] = 'gtm4wp.changeDetailViewEEC';
409
- $dataLayer['ecommerce'] = array(
410
- 'currencyCode' => $currencyCode,
411
- 'detail' => array(
412
- 'products' => array(
413
- $eec_product_array
414
- )
415
- )
416
- );
417
- }
418
- }
419
- }
420
- }
421
- } elseif ( is_cart() ) {
422
- if (
423
- $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ]
424
- || $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEECCARTASFIRSTSTEP ]
425
- || $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ]
426
- ) {
427
- $gtm4wp_cart_products = array();
428
- $gtm4wp_cart_products_remarketing = array();
429
-
430
- $gtm4wp_currency = get_woocommerce_currency();
431
-
432
- foreach ( $woo->cart->get_cart() as $cart_item_id => $cart_item_data ) {
433
- $product = apply_filters( 'woocommerce_cart_item_product', $cart_item_data['data'], $cart_item_data, $cart_item_id );
434
-
435
- if ( ! apply_filters( GTM4WP_WPFILTER_EEC_CART_ITEM, true, $cart_item_data ) ) {
436
- continue;
437
- }
438
-
439
- $eec_product_array = gtm4wp_process_product( $product, array(
440
- 'quantity' => $cart_item_data['quantity']
441
- ), 'cart' );
442
-
443
- $gtm4wp_cart_products[] = $eec_product_array;
444
- $gtm4wp_cart_products_remarketing[] = gtm4wp_prefix_productid( $eec_product_array[ 'id' ] );
445
- }
446
-
447
- if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ] ) {
448
- $dataLayer['ecomm_prodid'] = $gtm4wp_cart_products_remarketing;
449
- $dataLayer['ecomm_pagetype'] = 'cart';
450
- if ( ! $woo->cart->prices_include_tax ) {
451
- $cart_total = $woo->cart->cart_contents_total;
452
- } else {
453
- $cart_total = $woo->cart->cart_contents_total + $woo->cart->tax_total;
454
- }
455
- $dataLayer['ecomm_totalvalue'] = (float) $cart_total;
456
- }
457
-
458
- if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) {
459
- if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEECCARTASFIRSTSTEP ] ) {
460
- $dataLayer['event'] = 'gtm4wp.checkoutStepEEC';
461
- $dataLayer['ecommerce'] = array(
462
- 'currencyCode' => $gtm4wp_currency,
463
- 'checkout' => array(
464
- 'actionField' => array(
465
- 'step' => 1,
466
- ),
467
- 'products' => $gtm4wp_cart_products,
468
- )
469
- );
470
- } else {
471
- // add only ga4 products to populate view_cart event
472
- $dataLayer['ecommerce'] = array(
473
- 'cart' => $gtm4wp_cart_products
474
- );
475
- }
476
- }
477
- }
478
- } elseif ( is_order_received_page() ) {
479
- $do_not_flag_tracked_order = (bool) ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCNOORDERTRACKEDFLAG ] );
480
- $order_id = empty( $_GET['order'] ) ? ( $GLOBALS['wp']->query_vars['order-received'] ? $GLOBALS['wp']->query_vars['order-received'] : 0 ) : absint( $_GET['order'] );
481
- $order_id_filtered = apply_filters( 'woocommerce_thankyou_order_id', $order_id );
482
- if ( '' != $order_id_filtered ) {
483
- $order_id = $order_id_filtered;
484
- }
485
-
486
- $order_key = apply_filters( 'woocommerce_thankyou_order_key', empty( $_GET['key'] ) ? '' : wc_clean( $_GET['key'] ) );
487
-
488
- if ( $order_id > 0 ) {
489
- $order = wc_get_order( $order_id );
490
-
491
- if ( $order instanceof WC_Order ) {
492
- $this_order_key = $order->get_order_key();
493
-
494
- if ( $this_order_key != $order_key ) {
495
- unset( $order );
496
- }
497
- } else {
498
- unset( $order );
499
- }
500
- }
501
-
502
- if(isset($order) && $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCORDERMAXAGE ] ){
503
-
504
- $now = new DateTime();
505
- if($order->is_paid() && $order->get_date_paid()){
506
- $diff = $now->diff($order->get_date_paid());
507
- $minutes = ($diff->days * 24 * 60) + ($diff->h * 60) + $diff->i;
508
- } else {
509
- $diff = $now->diff($order->get_date_created());
510
- $minutes = ($diff->days * 24 * 60) + ($diff->h * 60) + $diff->i;
511
- }
512
-
513
- if($minutes > $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCORDERMAXAGE ]) {
514
- unset($order);
515
- }
516
- }
517
-
518
- if ( isset($order) && $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCORDERDATA ] ) {
519
- $order_items = gtm4wp_process_order_items( $order );
520
-
521
- $dataLayer['orderData'] = array(
522
- 'attributes' => array(
523
- 'date' => $order->get_date_created()->date( 'c' ),
524
-
525
- 'order_number' => $order->get_order_number(),
526
- 'order_key' => $order->get_order_key(),
527
-
528
- 'payment_method' => esc_js( $order->get_payment_method() ),
529
- 'payment_method_title' => esc_js( $order->get_payment_method_title() ),
530
-
531
- 'shipping_method' => esc_js( $order->get_shipping_method() ),
532
-
533
- 'status' => esc_js( $order->get_status() ),
534
-
535
- 'coupons' => implode( ', ', ( $gtm4wp_is_woocommerce3_7 ? $order->get_coupon_codes() : $order->get_used_coupons() ) )
536
- ),
537
- 'totals' => array(
538
- 'currency' => esc_js( $order->get_currency() ),
539
- 'discount_total' => esc_js( $order->get_discount_total() ),
540
- 'discount_tax' => esc_js( $order->get_discount_tax() ),
541
- 'shipping_total' => esc_js( $order->get_shipping_total() ),
542
- 'shipping_tax' => esc_js( $order->get_shipping_tax() ),
543
- 'cart_tax' => esc_js( $order->get_cart_tax() ),
544
- 'total' => esc_js( $order->get_total() ),
545
- 'total_tax' => esc_js( $order->get_total_tax() ),
546
- 'total_discount' => esc_js( $order->get_total_discount() ),
547
- 'subtotal' => esc_js( $order->get_subtotal() ),
548
- 'tax_totals' => $order->get_tax_totals()
549
- ),
550
- 'customer' => array(
551
- 'id' => $order->get_customer_id(),
552
-
553
- 'billing' => array(
554
- 'first_name' => esc_js( $order->get_billing_first_name() ),
555
- 'last_name' => esc_js( $order->get_billing_last_name() ),
556
- 'company' => esc_js( $order->get_billing_company() ),
557
- 'address_1' => esc_js( $order->get_billing_address_1() ),
558
- 'address_2' => esc_js( $order->get_billing_address_2() ),
559
- 'city' => esc_js( $order->get_billing_city() ),
560
- 'state' => esc_js( $order->get_billing_state() ),
561
- 'postcode' => esc_js( $order->get_billing_postcode() ),
562
- 'country' => esc_js( $order->get_billing_country() ),
563
- 'email' => esc_js( $order->get_billing_email() ),
564
- 'phone' => esc_js( $order->get_billing_phone() )
565
- ),
566
-
567
- 'shipping' => array(
568
- 'first_name' => esc_js( $order->get_shipping_first_name() ),
569
- 'last_name' => esc_js( $order->get_shipping_last_name() ),
570
- 'company' => esc_js( $order->get_shipping_company() ),
571
- 'address_1' => esc_js( $order->get_shipping_address_1() ),
572
- 'address_2' => esc_js( $order->get_shipping_address_2() ),
573
- 'city' => esc_js( $order->get_shipping_city() ),
574
- 'state' => esc_js( $order->get_shipping_state() ),
575
- 'postcode' => esc_js( $order->get_shipping_postcode() ),
576
- 'country' => esc_js( $order->get_shipping_country() )
577
- )
578
-
579
- ),
580
- 'items' => $order_items['products']
581
- );
582
- }
583
-
584
- if ( ( 1 == get_post_meta( $order_id, '_ga_tracked', true ) ) && ! $do_not_flag_tracked_order ) {
585
- unset( $order );
586
- }
587
-
588
- if ( isset( $_COOKIE[ 'gtm4wp_orderid_tracked' ] ) && ( $_COOKIE[ 'gtm4wp_orderid_tracked' ] == $order_id ) && ! $do_not_flag_tracked_order ) {
589
- unset( $order );
590
- }
591
-
592
- if ( isset( $order ) ) {
593
- if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEXCLUDETAX ] ) {
594
- $order_revenue = (float)( $order->get_total() - $order->get_total_tax() );
595
- } else {
596
- $order_revenue = (float) $order->get_total();
597
- }
598
-
599
- $order_shipping_cost = (float) $order->get_shipping_total();
600
-
601
- if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEXCLUDESHIPPING ] ) {
602
- $order_revenue -= $order_shipping_cost;
603
- }
604
-
605
- $order_currency = $order->get_currency();
606
-
607
- if ( true === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKCLASSICEC ] ) {
608
- $dataLayer['event'] = 'gtm4wp.orderCompleted';
609
- $dataLayer['transactionId'] = $order->get_order_number();
610
- $dataLayer['transactionAffiliation'] = '';
611
- $dataLayer['transactionTotal'] = $order_revenue;
612
- $dataLayer['transactionShipping'] = $order_shipping_cost;
613
- $dataLayer['transactionTax'] = (float) $order->get_total_tax();
614
- $dataLayer['transactionCurrency'] = $order_currency;
615
- }
616
-
617
- if ( true === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) {
618
- $dataLayer['event'] = 'gtm4wp.orderCompletedEEC';
619
- $dataLayer['ecommerce'] = array(
620
- 'currencyCode' => $order_currency,
621
- 'purchase' => array(
622
- 'actionField' => array(
623
- 'id' => $order->get_order_number(),
624
- 'affiliation' => '',
625
- 'revenue' => $order_revenue,
626
- 'tax' => (float) $order->get_total_tax(),
627
- 'shipping' => (float)( $order->get_shipping_total() ),
628
- 'coupon' => implode( ', ', ( $gtm4wp_is_woocommerce3_7 ? $order->get_coupon_codes() : $order->get_used_coupons() ) ),
629
- )
630
- )
631
- );
632
- }
633
-
634
- if ( ! isset( $order_items ) ) {
635
- $order_items = gtm4wp_process_order_items( $order );
636
- }
637
-
638
- if ( true === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKCLASSICEC ] ) {
639
- $dataLayer['transactionProducts'] = $order_items['products'];
640
- }
641
-
642
- if ( true === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) {
643
- $dataLayer['ecommerce']['purchase']['products'] = $order_items['products'];
644
- }
645
-
646
- if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ] ) {
647
- $dataLayer['ecomm_prodid'] = $order_items['product_ids'];
648
- $dataLayer['ecomm_pagetype'] = 'purchase';
649
- $dataLayer['ecomm_totalvalue'] = (float) $order_items['sumprice'];
650
- }
651
-
652
- if ( ! $do_not_flag_tracked_order ) {
653
- update_post_meta( $order_id, '_ga_tracked', 1 );
654
- }
655
- }
656
- } elseif ( is_checkout() ) {
657
- if (
658
- ( true === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] )
659
- || ( true === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ] )
660
- ) {
661
- $gtm4wp_checkout_products = array();
662
- $gtm4wp_checkout_products_remarketing = array();
663
- $gtm4wp_totalvalue = 0;
664
-
665
- foreach ( $woo->cart->get_cart() as $cart_item_id => $cart_item_data ) {
666
- $product = apply_filters( 'woocommerce_cart_item_product', $cart_item_data['data'], $cart_item_data, $cart_item_id );
667
-
668
- if ( ! apply_filters( GTM4WP_WPFILTER_EEC_CART_ITEM, true, $cart_item_data ) ) {
669
- continue;
670
- }
671
-
672
- $eec_product_array = gtm4wp_process_product( $product, array(
673
- 'quantity' => $cart_item_data['quantity']
674
- ), 'cart' );
675
-
676
- $gtm4wp_checkout_products[] = $eec_product_array;
677
-
678
- $gtm4wp_checkout_products_remarketing[] = gtm4wp_prefix_productid( $eec_product_array[ 'id' ] );
679
- $gtm4wp_totalvalue += $eec_product_array['quantity'] * $eec_product_array['price'];
680
- } // end foreach cart item
681
-
682
- if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ] ) {
683
- $dataLayer['ecomm_prodid'] = $gtm4wp_checkout_products_remarketing;
684
- $dataLayer['ecomm_pagetype'] = 'cart';
685
- $dataLayer['ecomm_totalvalue'] = (float) $gtm4wp_totalvalue;
686
- }
687
-
688
- if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) {
689
- $currencyCode = get_woocommerce_currency();
690
-
691
- $ga4_products = array();
692
- $sum_value = 0;
693
- foreach( $gtm4wp_checkout_products as $oneproduct ) {
694
- $ga4_products[] = gtm4wp_map_eec_to_ga4( $oneproduct );
695
- $sum_value += $oneproduct["price"] * $oneproduct["quantity"];
696
- }
697
-
698
- $dataLayer['event'] = 'gtm4wp.checkoutStepEEC';
699
- $dataLayer['ecommerce'] = array(
700
- 'currencyCode' => $currencyCode,
701
- 'checkout' => array(
702
- 'actionField' => array(
703
- 'step' => 1 + (int) $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEECCARTASFIRSTSTEP ],
704
- ),
705
- 'products' => $gtm4wp_checkout_products,
706
- )
707
- );
708
-
709
- wc_enqueue_js('
710
- window.gtm4wp_checkout_products = ' . json_encode( $gtm4wp_checkout_products ) . ';
711
- window.gtm4wp_checkout_products_ga4 = ' . json_encode( $ga4_products ) . ';
712
- window.gtm4wp_checkout_value = ' . (float) $sum_value . ';
713
- window.gtm4wp_checkout_step_offset = ' . (int) $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEECCARTASFIRSTSTEP ] . ';'
714
- );
715
- }
716
- }
717
- } else {
718
- if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ] ) {
719
- $dataLayer['ecomm_pagetype'] = 'other';
720
- }
721
- }
722
-
723
- if ( isset( $_COOKIE['gtm4wp_product_readded_to_cart'] ) ) {
724
- $cart_item = $woo->cart->get_cart_item( $_COOKIE['gtm4wp_product_readded_to_cart'] );
725
- if ( ! empty( $cart_item ) ) {
726
- $product = $cart_item['data'];
727
-
728
- $eec_product_array = gtm4wp_process_product( $product, array(
729
- 'quantity' => $cart_item['quantity']
730
- ), 'readdedtocart' );
731
-
732
- $currencyCode = get_woocommerce_currency();
733
-
734
- $dataLayer['event'] = 'gtm4wp.addProductToCartEEC';
735
- $dataLayer['ecommerce'] = array(
736
- 'currencyCode' => $currencyCode,
737
- 'add' => array(
738
- 'products' => array(
739
- $eec_product_array
740
- )
741
- )
742
- );
743
- }
744
-
745
- wc_enqueue_js( "document.cookie = 'gtm4wp_product_readded_to_cart=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';" );
746
- unset( $_COOKIE['gtm4wp_product_readded_to_cart'] );
747
- }
748
-
749
- return $dataLayer;
750
- }
751
-
752
- function gtm4wp_woocommerce_single_add_to_cart_tracking() {
753
- global $product, $gtm4wp_datalayer_name, $gtm4wp_options;
754
-
755
- // exit early if there is nothing to do
756
- if ( ( false === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKCLASSICEC ] ) && ( false === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) ) {
757
- return;
758
- }
759
-
760
- $eec_product_array = gtm4wp_process_product( $product, array(), 'addtocartsingle' );
761
-
762
- foreach ( $eec_product_array as $eec_product_array_key => $eec_product_array_value ) {
763
- echo '<input type="hidden" name="gtm4wp_' . esc_attr( $eec_product_array_key ) . '" value="' . esc_attr( $eec_product_array_value ) . '" />' . "\n";
764
- }
765
- }
766
-
767
- $GLOBALS['gtm4wp_cart_item_proddata'] = '';
768
- function gtm4wp_woocommerce_cart_item_product_filter( $product, $cart_item = '', $cart_id = '' ) {
769
- global $gtm4wp_options;
770
-
771
- $eec_product_array = gtm4wp_process_product( $product, array(
772
- 'productlink' => apply_filters( 'the_permalink', get_permalink(), 0 )
773
- ), 'cart' );
774
-
775
- $GLOBALS['gtm4wp_cart_item_proddata'] = $eec_product_array;
776
-
777
- return $product;
778
- }
779
-
780
- function gtm4wp_woocommerce_cart_item_remove_link_filter( $remove_from_cart_link ) {
781
- if ( ! isset( $GLOBALS['gtm4wp_cart_item_proddata'] ) ) {
782
- return $remove_from_cart_link;
783
- }
784
-
785
- if ( ! is_array( $GLOBALS['gtm4wp_cart_item_proddata'] ) ) {
786
- return $remove_from_cart_link;
787
- }
788
-
789
- if ( ! isset( $GLOBALS['gtm4wp_cart_item_proddata']['variant'] ) ) {
790
- $GLOBALS['gtm4wp_cart_item_proddata']['variant'] = '';
791
- }
792
-
793
- if ( ! isset( $GLOBALS['gtm4wp_cart_item_proddata']['brand'] ) ) {
794
- $GLOBALS['gtm4wp_cart_item_proddata']['brand'] = '';
795
- }
796
-
797
- $cartlink_with_data = sprintf(
798
- 'data-gtm4wp_product_id="%s" data-gtm4wp_product_name="%s" data-gtm4wp_product_price="%s" data-gtm4wp_product_cat="%s" data-gtm4wp_product_url="%s" data-gtm4wp_product_variant="%s" data-gtm4wp_product_stocklevel="%s" data-gtm4wp_product_brand="%s" href="',
799
- esc_attr( $GLOBALS['gtm4wp_cart_item_proddata']['id'] ),
800
- esc_attr( $GLOBALS['gtm4wp_cart_item_proddata']['name'] ),
801
- esc_attr( $GLOBALS['gtm4wp_cart_item_proddata']['price'] ),
802
- esc_attr( $GLOBALS['gtm4wp_cart_item_proddata']['category'] ),
803
- esc_url( $GLOBALS['gtm4wp_cart_item_proddata']['productlink'] ),
804
- esc_attr( $GLOBALS['gtm4wp_cart_item_proddata']['variant'] ),
805
- esc_attr( $GLOBALS['gtm4wp_cart_item_proddata']['stocklevel'] ),
806
- esc_attr( $GLOBALS['gtm4wp_cart_item_proddata']['brand'] )
807
- );
808
- $GLOBALS['gtm4wp_cart_item_proddata'] = '';
809
-
810
- return gtm4wp_str_replace_first( 'href="', $cartlink_with_data, $remove_from_cart_link );
811
- }
812
-
813
- function gtp4wp_woocommerce_reset_loop() {
814
- global $woocommerce_loop;
815
-
816
- $woocommerce_loop['listtype'] = '';
817
- }
818
-
819
- function gtm4wp_woocommerce_add_related_to_loop( $arg ) {
820
- global $woocommerce_loop;
821
-
822
- $woocommerce_loop['listtype'] = __( 'Related Products', 'duracelltomi-google-tag-manager' );
823
-
824
- return $arg;
825
- }
826
-
827
- function gtm4wp_woocommerce_add_cross_sell_to_loop( $arg ) {
828
- global $woocommerce_loop;
829
-
830
- $woocommerce_loop['listtype'] = __( 'Cross-Sell Products', 'duracelltomi-google-tag-manager' );
831
-
832
- return $arg;
833
- }
834
-
835
- function gtm4wp_woocommerce_add_upsells_to_loop( $arg ) {
836
- global $woocommerce_loop;
837
-
838
- $woocommerce_loop['listtype'] = __( 'Upsell Products', 'duracelltomi-google-tag-manager' );
839
-
840
- return $arg;
841
- }
842
-
843
- function gtm4wp_woocommerce_before_template_part( $template_name ) {
844
- ob_start();
845
- }
846
-
847
- function gtm4wp_woocommerce_after_template_part( $template_name ) {
848
- global $product, $gtm4wp_product_counter, $gtm4wp_last_widget_title, $gtm4wp_options;
849
-
850
- $productitem = ob_get_contents();
851
- ob_end_clean();
852
-
853
- if ( 'content-widget-product.php' == $template_name ) {
854
- $eec_product_array = gtm4wp_process_product( $product, array(
855
- 'productlink' => apply_filters( 'the_permalink', get_permalink(), 0 ),
856
- 'listname' => $gtm4wp_last_widget_title,
857
- 'listposition' => $gtm4wp_product_counter
858
- ), 'widgetproduct' );
859
-
860
- if ( ! isset( $eec_product_array[ 'brand' ] ) ) {
861
- $eec_product_array[ 'brand' ] = '';
862
- }
863
-
864
- $productlink_with_data = sprintf(
865
- 'data-gtm4wp_product_id="%s" data-gtm4wp_product_name="%s" data-gtm4wp_product_price="%s" data-gtm4wp_product_cat="%s" data-gtm4wp_product_url="%s" data-gtm4wp_productlist_name="%s" data-gtm4wp_product_listposition="%s" data-gtm4wp_product_stocklevel="%s" data-gtm4wp_product_brand="%s" href="',
866
- esc_attr( $eec_product_array['id'] ),
867
- esc_attr( $eec_product_array['name'] ),
868
- esc_attr( $eec_product_array['price'] ),
869
- esc_attr( $eec_product_array['category'] ),
870
- esc_url( $eec_product_array['productlink'] ),
871
- esc_attr( $eec_product_array['listname'] ),
872
- esc_attr( $eec_product_array['listposition'] ),
873
- esc_attr( $eec_product_array['stocklevel'] ),
874
- esc_attr( $eec_product_array[ "brand" ] )
875
- );
876
-
877
- $gtm4wp_product_counter++;
878
-
879
- $productitem = str_replace( 'href="', $productlink_with_data, $productitem );
880
- }
881
-
882
- echo $productitem;
883
- }
884
-
885
- function gtm4wp_widget_title_filter( $widget_title ) {
886
- global $gtm4wp_product_counter, $gtm4wp_last_widget_title;
887
-
888
- $gtm4wp_product_counter = 1;
889
- $gtm4wp_last_widget_title = $widget_title . __( ' (widget)', 'duracelltomi-google-tag-manager' );
890
-
891
- return $widget_title;
892
- }
893
-
894
- function gtm4wp_before_recent_products_loop() {
895
- global $woocommerce_loop;
896
-
897
- $woocommerce_loop['listtype'] = __( 'Recent Products', 'duracelltomi-google-tag-manager' );
898
- }
899
-
900
- function gtm4wp_before_sale_products_loop() {
901
- global $woocommerce_loop;
902
-
903
- $woocommerce_loop['listtype'] = __( 'Sale Products', 'duracelltomi-google-tag-manager' );
904
- }
905
-
906
- function gtm4wp_before_best_selling_products_loop() {
907
- global $woocommerce_loop;
908
-
909
- $woocommerce_loop['listtype'] = __( 'Best Selling Products', 'duracelltomi-google-tag-manager' );
910
- }
911
-
912
- function gtm4wp_before_top_rated_products_loop() {
913
- global $woocommerce_loop;
914
-
915
- $woocommerce_loop['listtype'] = __( 'Top Rated Products', 'duracelltomi-google-tag-manager' );
916
- }
917
-
918
- function gtm4wp_before_featured_products_loop() {
919
- global $woocommerce_loop;
920
-
921
- $woocommerce_loop['listtype'] = __( 'Featured Products', 'duracelltomi-google-tag-manager' );
922
- }
923
-
924
- function gtm4wp_before_related_products_loop() {
925
- global $woocommerce_loop;
926
-
927
- $woocommerce_loop['listtype'] = __( 'Related Products', 'duracelltomi-google-tag-manager' );
928
- }
929
-
930
- function gtm4wp_woocommerce_before_shop_loop_item() {
931
- global $product, $woocommerce_loop, $wp_query, $gtm4wp_options;
932
-
933
- if ( ! isset( $product ) ) {
934
- return;
935
- }
936
-
937
- $product_id = $product->get_id();
938
-
939
- $product_cat = '';
940
- if ( is_product_category() ) {
941
- global $wp_query;
942
- $cat_obj = $wp_query->get_queried_object();
943
- if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCUSEFULLCATEGORYPATH ] ) {
944
- $product_cat = gtm4wp_get_product_category_hierarchy( $cat_obj->term_id );
945
- } else {
946
- $product_cat = $cat_obj->name;
947
- }
948
- } else {
949
- $product_cat = gtm4wp_get_product_category( $product_id, $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCUSEFULLCATEGORYPATH ] );
950
- }
951
-
952
- if ( is_search() ) {
953
- $list_name = __( 'Search Results', 'duracelltomi-google-tag-manager' );
954
- } elseif ( isset( $woocommerce_loop['listtype'] ) && ( $woocommerce_loop['listtype'] != '' ) ) {
955
- $list_name = $woocommerce_loop['listtype'];
956
- } else {
957
- $list_name = __( 'General Product List', 'duracelltomi-google-tag-manager' );
958
- }
959
-
960
- $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
961
- $posts_per_page = get_query_var( 'posts_per_page' );
962
- if ( $posts_per_page < 1 ) {
963
- $posts_per_page = 1;
964
- }
965
-
966
- $eec_product_array = gtm4wp_process_product( $product, array(
967
- 'productlink' => apply_filters( 'the_permalink', get_permalink(), 0 ),
968
- 'listname' => $list_name,
969
- 'listposition' => $woocommerce_loop['loop'] + ( $posts_per_page * ( $paged - 1 ) )
970
- ), 'productlist' );
971
-
972
- if ( ! isset( $eec_product_array[ 'brand' ] ) ) {
973
- $eec_product_array[ 'brand' ] = '';
974
- }
975
-
976
- printf(
977
- '<span class="gtm4wp_productdata" style="display:none; visibility:hidden;" data-gtm4wp_product_id="%s" data-gtm4wp_product_name="%s" data-gtm4wp_product_price="%s" data-gtm4wp_product_cat="%s" data-gtm4wp_product_url="%s" data-gtm4wp_product_listposition="%s" data-gtm4wp_productlist_name="%s" data-gtm4wp_product_stocklevel="%s" data-gtm4wp_product_brand="%s"></span>',
978
- esc_attr( $eec_product_array['id'] ),
979
- esc_attr( $eec_product_array['name'] ),
980
- esc_attr( $eec_product_array['price'] ),
981
- esc_attr( $eec_product_array['category'] ),
982
- esc_url( $eec_product_array['productlink'] ),
983
- esc_attr( $eec_product_array['listposition'] ),
984
- esc_attr( $eec_product_array['listname'] ),
985
- esc_attr( $eec_product_array['stocklevel'] ),
986
- esc_attr( $eec_product_array[ "brand" ] )
987
- );
988
- }
989
-
990
- function gtm4wp_woocommerce_cart_item_restored( $cart_item_key ) {
991
- setcookie( 'gtm4wp_product_readded_to_cart', $cart_item_key );
992
- }
993
-
994
- function gtm4wp_woocommerce_enqueue_scripts() {
995
- global $gtm4wp_options, $gtp4wp_plugin_url;
996
-
997
- if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKCLASSICEC ] ) {
998
- $in_footer = apply_filters( 'gtm4wp_' . GTM4WP_OPTION_INTEGRATE_WCTRACKCLASSICEC, false );
999
- wp_enqueue_script( 'gtm4wp-woocommerce-classic', $gtp4wp_plugin_url . 'js/gtm4wp-woocommerce-classic.js', array( 'jquery' ), GTM4WP_VERSION, $in_footer );
1000
- }
1001
-
1002
- if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) {
1003
- $in_footer = apply_filters( 'gtm4wp_' . GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC, false );
1004
- wp_enqueue_script( 'gtm4wp-woocommerce-enhanced', $gtp4wp_plugin_url . 'js/gtm4wp-woocommerce-enhanced.js', array( 'jquery' ), GTM4WP_VERSION, $in_footer );
1005
- }
1006
- }
1007
-
1008
- function gtm4wp_wc_quick_view_before_single_product() {
1009
- global $gtm4wp_options, $gtm4wp_datalayer_name;
1010
-
1011
- $dataLayer = array(
1012
- 'event' => 'gtm4wp.changeDetailViewEEC',
1013
- );
1014
-
1015
- if ( ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ] ) || ( true === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) ) {
1016
- $postid = get_the_ID();
1017
- $product = wc_get_product( $postid );
1018
-
1019
- $eec_product_array = gtm4wp_process_product( $product, array(), 'productdetail' );
1020
-
1021
- $dataLayer['productRatingCounts'] = $product->get_rating_counts();
1022
- $dataLayer['productAverageRating'] = (float) $product->get_average_rating();
1023
- $dataLayer['productReviewCount'] = (int) $product->get_review_count();
1024
- $dataLayer['productType'] = $product->get_type();
1025
-
1026
- switch ( $dataLayer['productType'] ) {
1027
- case 'variable': {
1028
- $dataLayer['productIsVariable'] = 1;
1029
-
1030
- $dataLayer['ecomm_prodid'] = gtm4wp_prefix_productid( $eec_product_array[ 'id' ] );
1031
- $dataLayer['ecomm_pagetype'] = 'product';
1032
- $dataLayer['ecomm_totalvalue'] = $eec_product_array[ 'price' ];
1033
-
1034
- break;
1035
- }
1036
-
1037
- case 'grouped': {
1038
- $dataLayer['productIsVariable'] = 0;
1039
-
1040
- break;
1041
- }
1042
-
1043
- default: {
1044
- $dataLayer['productIsVariable'] = 0;
1045
-
1046
- if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ] ) {
1047
- $dataLayer['ecomm_prodid'] = gtm4wp_prefix_productid( $eec_product_array[ 'id' ] );
1048
- $dataLayer['ecomm_pagetype'] = 'product';
1049
- $dataLayer['ecomm_totalvalue'] = $eec_product_array['price'];
1050
- }
1051
-
1052
- if ( true === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) {
1053
- $currencyCode = get_woocommerce_currency();
1054
-
1055
- $dataLayer['ecommerce'] = array(
1056
- 'currencyCode' => $currencyCode,
1057
- 'detail' => array(
1058
- 'products' => array(
1059
- $eec_product_array
1060
- )
1061
- )
1062
- );
1063
- }
1064
- }
1065
- }
1066
- }
1067
-
1068
- echo '
1069
- <script>
1070
- ' . $gtm4wp_datalayer_name . '.push(' . json_encode( $dataLayer ) . ');
1071
- </script>';
1072
- }
1073
-
1074
- function gtm4wp_woocommerce_grouped_product_list_column_label( $labelvalue, $product ) {
1075
- global $gtm4wp_options, $gtm4wp_grouped_product_ix;
1076
-
1077
- if ( ! isset( $product ) ) {
1078
- return $labelvalue;
1079
- }
1080
-
1081
- $list_name = __( 'Grouped Product Detail Page', 'duracelltomi-google-tag-manager' );
1082
-
1083
- $eec_product_array = gtm4wp_process_product( $product, array(
1084
- 'productlink' => $product->get_permalink(),
1085
- 'listname' => $list_name,
1086
- 'listposition' => $gtm4wp_grouped_product_ix
1087
- ), 'groupedproductlist' );
1088
-
1089
- $gtm4wp_grouped_product_ix++;
1090
-
1091
- if ( ! isset( $eec_product_array[ 'brand' ] ) ) {
1092
- $eec_product_array[ 'brand' ] = '';
1093
- }
1094
-
1095
- $labelvalue .=
1096
- sprintf(
1097
- '<span class="gtm4wp_productdata" style="display:none; visibility:hidden;" data-gtm4wp_product_id="%s" data-gtm4wp_product_sku="%s" data-gtm4wp_product_name="%s" data-gtm4wp_product_price="%s" data-gtm4wp_product_cat="%s" data-gtm4wp_product_url="%s" data-gtm4wp_product_listposition="%s" data-gtm4wp_productlist_name="%s" data-gtm4wp_product_stocklevel="%s" data-gtm4wp_product_brand="%s"></span>',
1098
- esc_attr( $eec_product_array['id'] ),
1099
- esc_attr( $eec_product_array['sku'] ),
1100
- esc_attr( $eec_product_array['name'] ),
1101
- esc_attr( $eec_product_array['price'] ),
1102
- esc_attr( $eec_product_array['category'] ),
1103
- esc_url( $eec_product_array['productlink'] ),
1104
- esc_attr( $eec_product_array['listposition'] ),
1105
- esc_attr( $eec_product_array['listname'] ),
1106
- esc_attr( $eec_product_array['stocklevel'] ),
1107
- esc_attr( $eec_product_array['brand'] )
1108
- );
1109
-
1110
- return $labelvalue;
1111
- }
1112
-
1113
- // do not add filter if someone enabled WooCommerce integration without an activated WooCommerce plugin
1114
- if ( function_exists( 'WC' ) ) {
1115
- add_filter( GTM4WP_WPFILTER_COMPILE_DATALAYER, 'gtm4wp_woocommerce_datalayer_filter_items' );
1116
-
1117
- add_filter( 'loop_end', 'gtp4wp_woocommerce_reset_loop' );
1118
- add_action( 'woocommerce_before_shop_loop_item', 'gtm4wp_woocommerce_before_shop_loop_item' );
1119
- add_action( 'woocommerce_after_add_to_cart_button', 'gtm4wp_woocommerce_single_add_to_cart_tracking' );
1120
-
1121
- // add_action( "wp_footer", "gtm4wp_woocommerce_wp_footer" );
1122
- add_action( 'wp_enqueue_scripts', 'gtm4wp_woocommerce_enqueue_scripts' );
1123
- add_filter( GTM4WP_WPACTION_ADDGLOBALVARS, 'gtm4wp_woocommerce_addglobalvars' );
1124
-
1125
- if ( true === $GLOBALS['gtm4wp_options'][ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) {
1126
- // add_action( "wp_footer", "gtm4wp_woocommerce_enhanced_ecom_product_click" );
1127
- add_action( 'woocommerce_before_template_part', 'gtm4wp_woocommerce_before_template_part' );
1128
- add_action( 'woocommerce_after_template_part', 'gtm4wp_woocommerce_after_template_part' );
1129
- add_filter( 'widget_title', 'gtm4wp_widget_title_filter' );
1130
- add_action( 'wc_quick_view_before_single_product', 'gtm4wp_wc_quick_view_before_single_product' );
1131
- add_filter( 'woocommerce_grouped_product_list_column_label', 'gtm4wp_woocommerce_grouped_product_list_column_label', 10, 2 );
1132
-
1133
- add_filter( 'woocommerce_cart_item_product', 'gtm4wp_woocommerce_cart_item_product_filter' );
1134
- add_filter( 'woocommerce_cart_item_remove_link', 'gtm4wp_woocommerce_cart_item_remove_link_filter' );
1135
- add_action( 'woocommerce_cart_item_restored', 'gtm4wp_woocommerce_cart_item_restored' );
1136
-
1137
- add_filter( 'woocommerce_related_products_args', 'gtm4wp_woocommerce_add_related_to_loop' );
1138
- add_filter( 'woocommerce_related_products_columns', 'gtm4wp_woocommerce_add_related_to_loop' );
1139
- add_filter( 'woocommerce_cross_sells_columns', 'gtm4wp_woocommerce_add_cross_sell_to_loop' );
1140
- add_filter( 'woocommerce_upsells_columns', 'gtm4wp_woocommerce_add_upsells_to_loop' );
1141
-
1142
- add_action( 'woocommerce_shortcode_before_recent_products_loop', 'gtm4wp_before_recent_products_loop' );
1143
- add_action( 'woocommerce_shortcode_before_sale_products_loop', 'gtm4wp_before_sale_products_loop' );
1144
- add_action( 'woocommerce_shortcode_before_best_selling_products_loop', 'gtm4wp_before_best_selling_products_loop' );
1145
- add_action( 'woocommerce_shortcode_before_top_rated_products_loop', 'gtm4wp_before_top_rated_products_loop' );
1146
- add_action( 'woocommerce_shortcode_before_featured_products_loop', 'gtm4wp_before_featured_products_loop' );
1147
- add_action( 'woocommerce_shortcode_before_related_products_loop', 'gtm4wp_before_related_products_loop' );
1148
- }
1149
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ define( 'GTM4WP_WPFILTER_EEC_PRODUCT_ARRAY', 'gtm4wp_eec_product_array' );
3
+ define( 'GTM4WP_WPFILTER_EEC_CART_ITEM', 'gtm4wp_eec_cart_item' );
4
+ define( 'GTM4WP_WPFILTER_EEC_ORDER_ITEM', 'gtm4wp_eec_order_item' );
5
+
6
+ $gtm4wp_product_counter = 0;
7
+ $gtm4wp_last_widget_title = 'Sidebar Products';
8
+ if ( function_exists( 'WC' ) ) {
9
+ $GLOBALS['gtm4wp_is_woocommerce3_7'] = version_compare( WC()->version, '3.7', '>=' );
10
+ } else {
11
+ $GLOBALS['gtm4wp_is_woocommerce3_7'] = false;
12
+ }
13
+ $GLOBALS['gtm4wp_grouped_product_ix'] = 1;
14
+ $GLOBALS['gtm4wp_woocommerce_purchase_data_pushed'] = false;
15
+
16
+ // from https://snippets.webaware.com.au/ramblings/php-really-doesnt-unicode/
17
+ function gtm4wp_untexturize( $fancy ) {
18
+ $fixes = false;
19
+
20
+ if ( $fixes === false ) {
21
+ $fixes = array(
22
+ json_decode( '"\u201C"' ) => '"', // left double quotation mark
23
+ json_decode( '"\u201D"' ) => '"', // right double quotation mark
24
+ json_decode( '"\u2018"' ) => "'", // left single quotation mark
25
+ json_decode( '"\u2019"' ) => "'", // right single quotation mark
26
+ json_decode( '"\u2032"' ) => "'", // prime (minutes, feet)
27
+ json_decode( '"\u2033"' ) => '"', // double prime (seconds, inches)
28
+ json_decode( '"\u2013"' ) => '-', // en dash
29
+ json_decode( '"\u2014"' ) => '--', // em dash
30
+ );
31
+ }
32
+
33
+ $normal = strtr( $fancy, $fixes );
34
+
35
+ return $normal;
36
+ }
37
+
38
+ function gtm4wp_woocommerce_html_entity_decode( $val ) {
39
+ return gtm4wp_untexturize( html_entity_decode( $val, ENT_QUOTES, 'utf-8' ) );
40
+ }
41
+
42
+ function gtm4wp_prefix_productid( $product_id ) {
43
+ global $gtm4wp_options;
44
+
45
+ if ( '' != $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMPRODIDPREFIX ] ) {
46
+ return $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMPRODIDPREFIX ] . $product_id;
47
+ } else {
48
+ return $product_id;
49
+ }
50
+ }
51
+
52
+ // from https://stackoverflow.com/questions/1252693/using-str-replace-so-that-it-only-acts-on-the-first-match
53
+ function gtm4wp_str_replace_first( $from, $to, $subject ) {
54
+ $from = '/' . preg_quote( $from, '/' ) . '/';
55
+
56
+ return preg_replace( $from, $to, $subject, 1 );
57
+ }
58
+
59
+ function gtm4wp_get_product_category_hierarchy( $category_id ) {
60
+ $cat_hierarchy = '';
61
+
62
+ $category_parent_list = get_term_parents_list(
63
+ $category_id,
64
+ 'product_cat',
65
+ array(
66
+ 'format' => 'name',
67
+ 'separator' => '/',
68
+ 'link' => false,
69
+ 'inclusive' => true,
70
+ )
71
+ );
72
+
73
+ if ( is_string( $category_parent_list ) ) {
74
+ $cat_hierarchy = trim( $category_parent_list, '/' );
75
+ }
76
+
77
+ return $cat_hierarchy;
78
+ }
79
+
80
+ function gtm4wp_get_product_category( $product_id, $fullpath = false ) {
81
+ $product_cat = '';
82
+
83
+ $_product_cats = wp_get_post_terms( $product_id, 'product_cat', array( 'orderby' => 'parent', 'order' => 'ASC'));
84
+ if ( ( is_array( $_product_cats ) ) && ( count( $_product_cats ) > 0 ) ) {
85
+ $first_product_cat = array_pop( $_product_cats );
86
+ if ( $fullpath ) {
87
+ $product_cat = gtm4wp_get_product_category_hierarchy( $first_product_cat->term_id );
88
+ } else {
89
+ $product_cat = $first_product_cat->name;
90
+ }
91
+ }
92
+
93
+ return $product_cat;
94
+ }
95
+
96
+ function gtm4wp_woocommerce_getproductterm( $product_id, $taxonomy ) {
97
+ $gtm4wp_product_terms = wp_get_post_terms( $product_id, $taxonomy, array( 'orderby' => 'parent', 'order' => 'ASC'));
98
+ if ( is_array( $gtm4wp_product_terms ) && ( count( $gtm4wp_product_terms ) > 0 ) ) {
99
+ return $gtm4wp_product_terms[0]->name;
100
+ }
101
+
102
+ return "";
103
+ }
104
+
105
+ function gtm4wp_process_product( $product, $additional_product_attributes, $attributes_used_for ) {
106
+ global $gtm4wp_options;
107
+
108
+ if ( ! $product ) {
109
+ return false;
110
+ }
111
+
112
+ if ( ! ( $product instanceof WC_Product ) ) {
113
+ return false;
114
+ }
115
+
116
+ $product_id = $product->get_id();
117
+ $product_type = $product->get_type();
118
+ $remarketing_id = $product_id;
119
+ $product_sku = $product->get_sku();
120
+
121
+ if ( 'variation' == $product_type ) {
122
+ $parent_product_id = $product->get_parent_id();
123
+ $product_cat = gtm4wp_get_product_category( $parent_product_id, $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCUSEFULLCATEGORYPATH ] );
124
+ } else {
125
+ $product_cat = gtm4wp_get_product_category( $product_id, $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCUSEFULLCATEGORYPATH ] );
126
+ }
127
+
128
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCUSESKU ] && ( '' != $product_sku ) ) {
129
+ $remarketing_id = $product_sku;
130
+ }
131
+
132
+ $_temp_productdata = array(
133
+ 'id' => $remarketing_id,
134
+ 'name' => $product->get_title(),
135
+ 'sku' => $product_sku ? $product_sku : $product_id,
136
+ 'category' => $product_cat,
137
+ 'price' => round( (float) wc_get_price_to_display( $product ), 2),
138
+ 'stocklevel' => $product->get_stock_quantity()
139
+ );
140
+
141
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEECBRANDTAXONOMY ] != "" ) {
142
+ if ( isset( $parent_product_id ) && ( $parent_product_id !== 0 ) ) {
143
+ $product_id_to_query = $parent_product_id;
144
+ } else {
145
+ $product_id_to_query = $product_id;
146
+ }
147
+
148
+ $_temp_productdata[ "brand" ] = gtm4wp_woocommerce_getproductterm( $product_id_to_query, $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEECBRANDTAXONOMY ] );
149
+ }
150
+
151
+ if ( 'variation' == $product_type ) {
152
+ $_temp_productdata['variant'] = implode( ',', $product->get_variation_attributes() );
153
+ }
154
+
155
+ $_temp_productdata = array_merge( $_temp_productdata, $additional_product_attributes );
156
+
157
+ return apply_filters( GTM4WP_WPFILTER_EEC_PRODUCT_ARRAY, $_temp_productdata, $attributes_used_for );
158
+ }
159
+
160
+ function gtm4wp_get_gads_product_id_variable_name( $vertical_id ) {
161
+ global $gtm4wp_business_verticals_ids;
162
+
163
+ if ( array_key_exists( $vertical_id, $gtm4wp_business_verticals_ids ) ) {
164
+ return $gtm4wp_business_verticals_ids[ $vertical_id ];
165
+ } else {
166
+ return "id";
167
+ }
168
+ }
169
+
170
+ function gtm4wp_map_eec_to_ga4( $productdata ) {
171
+ global $gtm4wp_options;
172
+
173
+ if ( !is_array($productdata) ) {
174
+ return;
175
+ }
176
+
177
+ $category_path = array_key_exists( "category", $productdata ) ? $productdata[ "category" ] : "";
178
+ $category_parts = explode('/', $category_path);
179
+
180
+ // default, required parameters
181
+ $ga4_product = array(
182
+ 'item_id' => array_key_exists( "id", $productdata ) ? $productdata[ "id" ] : "",
183
+ 'item_name' => array_key_exists( "name", $productdata ) ? $productdata[ "name" ] : "",
184
+ 'item_brand' => array_key_exists( "brand", $productdata ) ? $productdata[ "brand" ] : "",
185
+ 'price' => array_key_exists( "price", $productdata ) ? $productdata[ "price" ] : ""
186
+ );
187
+
188
+ // category, also handle category path
189
+ if ( 1 == count($category_parts) ) {
190
+ $ga4_product[ "item_category" ] = $category_parts[0];
191
+ } else if ( count($category_parts) > 1 ) {
192
+ $ga4_product[ "item_category" ] = $category_parts[0];
193
+ for( $i=1; $i < min( 5, count( $category_parts ) ); $i++ ) {
194
+ $ga4_product[ "item_category_" . (string)($i+1) ] = $category_parts[$i];
195
+ }
196
+ }
197
+
198
+ // optional parameters which should not be included in the array if not set
199
+ if ( array_key_exists( "variant", $productdata ) ) {
200
+ $ga4_product[ "item_variant" ] = $productdata[ "variant" ];
201
+ }
202
+ if ( array_key_exists( "listname", $productdata ) ) {
203
+ $ga4_product[ "item_list_name" ] = $productdata[ "listname" ];
204
+ }
205
+ if ( array_key_exists( "listposition", $productdata ) ) {
206
+ $ga4_product[ "index" ] = $productdata[ "listposition" ];
207
+ }
208
+ if ( array_key_exists( "quantity", $productdata ) ) {
209
+ $ga4_product[ "quantity" ] = $productdata[ "quantity" ];
210
+ }
211
+ if ( array_key_exists( "coupon", $productdata ) ) {
212
+ $ga4_product[ "coupon" ] = $productdata[ "coupon" ];
213
+ }
214
+
215
+ $ga4_product[ "google_business_vertical" ] = $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCBUSINESSVERTICAL ];
216
+ $ga4_product[ gtm4wp_get_gads_product_id_variable_name( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCBUSINESSVERTICAL ] ) ] = gtm4wp_prefix_productid( $ga4_product["item_id"] );
217
+
218
+ return $ga4_product;
219
+ }
220
+
221
+ function gtm4wp_process_order_items( $order ) {
222
+ global $gtm4wp_options;
223
+
224
+ $return_data = array(
225
+ 'products' => [],
226
+ 'sumprice' => 0,
227
+ 'product_ids' => []
228
+ );
229
+
230
+ if ( ! $order ) {
231
+ return $return_data;
232
+ }
233
+
234
+ $order_items = $order->get_items();
235
+
236
+ if ( $order_items ) {
237
+ foreach ( $order_items as $item ) {
238
+ if ( ! apply_filters( GTM4WP_WPFILTER_EEC_ORDER_ITEM, true, $item ) ) {
239
+ continue;
240
+ }
241
+
242
+ $product = $item->get_product();
243
+ $inc_tax = ( 'incl' === get_option( 'woocommerce_tax_display_shop' ) );
244
+ $product_price = round( (float) $order->get_item_total( $item, $inc_tax ), 2);
245
+ $eec_product_array = gtm4wp_process_product( $product, array(
246
+ 'quantity' => $item->get_quantity(),
247
+ 'price' => $product_price
248
+ ), 'purchase' );
249
+
250
+ if ( $eec_product_array ) {
251
+ $return_data['products'][] = $eec_product_array;
252
+ $return_data['sumprice'] += $product_price * $eec_product_array['quantity'];
253
+ $return_data['product_ids'][] = gtm4wp_prefix_productid( $eec_product_array['id'] );
254
+ }
255
+ }
256
+ }
257
+
258
+ return $return_data;
259
+ }
260
+
261
+ function gtm4wp_woocommerce_addglobalvars( $return ) {
262
+ global $gtm4wp_options;
263
+
264
+ if ( function_exists( 'WC' ) && WC()->cart ) {
265
+ $gtm4wp_needs_shipping_address = (bool) WC()->cart->needs_shipping_address();
266
+ } else {
267
+ $gtm4wp_needs_shipping_address = false;
268
+ }
269
+
270
+ $return .= '
271
+ const gtm4wp_use_sku_instead = ' . (int) ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCUSESKU ] ) . ';
272
+ const gtm4wp_id_prefix = \'' . esc_js( gtm4wp_prefix_productid( '' ) ) . '\';
273
+ const gtm4wp_remarketing = ' . gtm4wp_escjs_boolean( (bool) ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ] ) ) . ';
274
+ const gtm4wp_eec = ' . gtm4wp_escjs_boolean( (bool) ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) ) . ';
275
+ const gtm4wp_classicec = ' . gtm4wp_escjs_boolean( (bool) ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKCLASSICEC ] ) ) . ';
276
+ const gtm4wp_currency = \'' . esc_js( get_woocommerce_currency() ) . '\';
277
+ const gtm4wp_product_per_impression = ' . (int) ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCPRODPERIMPRESSION ] ) . ';
278
+ const gtm4wp_needs_shipping_address = ' . gtm4wp_escjs_boolean( $gtm4wp_needs_shipping_address ) . ';
279
+ const gtm4wp_business_vertical = \'' . esc_js( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCBUSINESSVERTICAL ] ) . '\';
280
+ const gtm4wp_business_vertical_id = \'' . gtm4wp_get_gads_product_id_variable_name( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCBUSINESSVERTICAL ] ) . '\';';
281
+
282
+ return $return;
283
+ }
284
+
285
+ function gtm4wp_get_purchase_datalayer( $order, $order_items ) {
286
+ global $gtm4wp_options, $gtm4wp_is_woocommerce3_7;
287
+
288
+ $dataLayer = array();
289
+
290
+ if ( $order instanceof WC_Order ) {
291
+ $woo = WC();
292
+
293
+ // variable for Google Smart Shopping campaign new customer reporting
294
+ // https://support.google.com/google-ads/answer/9917012?hl=en-AU#zippy=%2Cinstall-with-google-tag-manager
295
+ if ( $woo->customer instanceof WC_Customer ) {
296
+ // 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
297
+ $woo_customer = new WC_Customer( $woo->customer->get_id() );
298
+ $dataLayer['new_customer'] = $woo_customer->get_order_count() === 1;
299
+ }
300
+
301
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEXCLUDETAX ] ) {
302
+ $order_revenue = (float)( $order->get_total() - $order->get_total_tax() );
303
+ } else {
304
+ $order_revenue = (float) $order->get_total();
305
+ }
306
+
307
+ $order_shipping_cost = (float) $order->get_shipping_total();
308
+
309
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEXCLUDESHIPPING ] ) {
310
+ $order_revenue -= $order_shipping_cost;
311
+ }
312
+
313
+ $order_currency = $order->get_currency();
314
+
315
+ if ( true === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKCLASSICEC ] ) {
316
+ $dataLayer['event'] = 'gtm4wp.orderCompleted';
317
+ $dataLayer['transactionId'] = $order->get_order_number();
318
+ $dataLayer['transactionAffiliation'] = '';
319
+ $dataLayer['transactionTotal'] = $order_revenue;
320
+ $dataLayer['transactionShipping'] = $order_shipping_cost;
321
+ $dataLayer['transactionTax'] = (float) $order->get_total_tax();
322
+ $dataLayer['transactionCurrency'] = $order_currency;
323
+ }
324
+
325
+ if ( true === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) {
326
+ $dataLayer['event'] = 'gtm4wp.orderCompletedEEC';
327
+ $dataLayer['ecommerce'] = array(
328
+ 'currencyCode' => $order_currency,
329
+ 'purchase' => array(
330
+ 'actionField' => array(
331
+ 'id' => $order->get_order_number(),
332
+ 'affiliation' => '',
333
+ 'revenue' => $order_revenue,
334
+ 'tax' => (float) $order->get_total_tax(),
335
+ 'shipping' => (float)( $order->get_shipping_total() ),
336
+ 'coupon' => implode( ', ', ( $gtm4wp_is_woocommerce3_7 ? $order->get_coupon_codes() : $order->get_used_coupons() ) ),
337
+ )
338
+ )
339
+ );
340
+ }
341
+
342
+ if ( isset( $order_items ) ) {
343
+ $_order_items = $order_items;
344
+ } else {
345
+ $_order_items = gtm4wp_process_order_items( $order );
346
+ }
347
+
348
+ if ( true === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKCLASSICEC ] ) {
349
+ $dataLayer['transactionProducts'] = $_order_items['products'];
350
+ }
351
+
352
+ if ( true === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) {
353
+ $dataLayer['ecommerce']['purchase']['products'] = $_order_items['products'];
354
+ }
355
+
356
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ] ) {
357
+ $dataLayer['ecomm_prodid'] = $_order_items['product_ids'];
358
+ $dataLayer['ecomm_pagetype'] = 'purchase';
359
+ $dataLayer['ecomm_totalvalue'] = (float) $_order_items['sumprice'];
360
+ }
361
+ }
362
+
363
+ return $dataLayer;
364
+ }
365
+
366
+ function gtm4wp_woocommerce_datalayer_filter_items( $dataLayer ) {
367
+ global $gtm4wp_options, $wp_query, $gtm4wp_datalayer_name, $gtm4wp_product_counter, $gtm4wp_is_woocommerce3_7;
368
+
369
+ if ( array_key_exists( "HTTP_X_REQUESTED_WITH", $_SERVER ) ) {
370
+ return $dataLayer;
371
+ }
372
+
373
+ $woo = WC();
374
+
375
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCCUSTOMERDATA ] ) {
376
+ if ( $woo->customer instanceof WC_Customer ) {
377
+ // 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
378
+ $woo_customer = new WC_Customer( $woo->customer->get_id() );
379
+
380
+ $dataLayer['customerTotalOrders'] = $woo_customer->get_order_count();
381
+ $dataLayer['customerTotalOrderValue'] = $woo_customer->get_total_spent();
382
+
383
+ $dataLayer['customerFirstName'] = $woo_customer->get_first_name();
384
+ $dataLayer['customerLastName'] = $woo_customer->get_last_name();
385
+
386
+ $dataLayer['customerBillingFirstName'] = $woo_customer->get_billing_first_name();
387
+ $dataLayer['customerBillingLastName'] = $woo_customer->get_billing_last_name();
388
+ $dataLayer['customerBillingCompany'] = $woo_customer->get_billing_company();
389
+ $dataLayer['customerBillingAddress1'] = $woo_customer->get_billing_address_1();
390
+ $dataLayer['customerBillingAddress2'] = $woo_customer->get_billing_address_2();
391
+ $dataLayer['customerBillingCity'] = $woo_customer->get_billing_city();
392
+ $dataLayer['customerBillingPostcode'] = $woo_customer->get_billing_postcode();
393
+ $dataLayer['customerBillingCountry'] = $woo_customer->get_billing_country();
394
+ $dataLayer['customerBillingEmail'] = $woo_customer->get_billing_email();
395
+ $dataLayer['customerBillingEmailHash'] = hash( 'sha256', $woo_customer->get_billing_email() );
396
+ $dataLayer['customerBillingPhone'] = $woo_customer->get_billing_phone();
397
+
398
+ $dataLayer['customerShippingFirstName'] = $woo_customer->get_shipping_first_name();
399
+ $dataLayer['customerShippingLastName'] = $woo_customer->get_shipping_last_name();
400
+ $dataLayer['customerShippingCompany'] = $woo_customer->get_shipping_company();
401
+ $dataLayer['customerShippingAddress1'] = $woo_customer->get_shipping_address_1();
402
+ $dataLayer['customerShippingAddress2'] = $woo_customer->get_shipping_address_2();
403
+ $dataLayer['customerShippingCity'] = $woo_customer->get_shipping_city();
404
+ $dataLayer['customerShippingPostcode'] = $woo_customer->get_shipping_postcode();
405
+ $dataLayer['customerShippingCountry'] = $woo_customer->get_shipping_country();
406
+ }
407
+ }
408
+
409
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEINCLUDECARTINDL ] && version_compare( $woo->version, "3.2", ">=" ) && isset($woo) && isset($woo->cart) ) {
410
+ $current_cart = $woo->cart;
411
+ $dataLayer["cartContent"] = array(
412
+ "totals" => array(
413
+ "applied_coupons" => $current_cart->get_applied_coupons(),
414
+ "discount_total" => $current_cart->get_discount_total(),
415
+ "subtotal" => $current_cart->get_subtotal(),
416
+ "total" => $current_cart->get_cart_contents_total()
417
+ ),
418
+ "items" => array()
419
+ );
420
+
421
+ foreach( $current_cart->get_cart() as $cart_item_id => $cart_item_data) {
422
+ $product = apply_filters( 'woocommerce_cart_item_product', $cart_item_data["data"], $cart_item_data, $cart_item_id );
423
+ if (
424
+ !apply_filters( GTM4WP_WPFILTER_EEC_CART_ITEM, true, $cart_item_data )
425
+ || !apply_filters( 'woocommerce_widget_cart_item_visible', true, $cart_item_data, $cart_item_id )
426
+ ) {
427
+ continue;
428
+ }
429
+
430
+ $eec_product_array = gtm4wp_process_product( $product, array(
431
+ 'quantity' => $cart_item_data["quantity"]
432
+ ), 'cart' );
433
+
434
+ $dataLayer["cartContent"]["items"][] = $eec_product_array;
435
+ }
436
+ }
437
+
438
+ if ( is_product_category() || is_product_tag() || is_front_page() || is_shop() ) {
439
+ $ecomm_pagetype = 'category';
440
+ if ( is_front_page() ) {
441
+ $ecomm_pagetype = 'home';
442
+ } elseif ( is_search() ) {
443
+ $ecomm_pagetype = 'searchresults';
444
+ }
445
+
446
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ] ) {
447
+ $dataLayer['ecomm_prodid'] = array();
448
+ $dataLayer['ecomm_pagetype'] = $ecomm_pagetype;
449
+ $dataLayer['ecomm_totalvalue'] = 0;
450
+ }
451
+ } elseif ( is_product() ) {
452
+ if (
453
+ $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ]
454
+ || ( true === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] )
455
+ ) {
456
+ $postid = get_the_ID();
457
+ $product = wc_get_product( $postid );
458
+
459
+ $eec_product_array = gtm4wp_process_product( $product, array(), 'productdetail' );
460
+
461
+ $dataLayer['productRatingCounts'] = $product->get_rating_counts();
462
+ $dataLayer['productAverageRating'] = (float) $product->get_average_rating();
463
+ $dataLayer['productReviewCount'] = (int) $product->get_review_count();
464
+ $dataLayer['productType'] = $product->get_type();
465
+
466
+ switch ( $dataLayer['productType'] ) {
467
+ case 'variable': {
468
+ $dataLayer['productIsVariable'] = 1;
469
+
470
+ $dataLayer['ecomm_prodid'] = gtm4wp_prefix_productid( $eec_product_array[ 'id' ] );
471
+ $dataLayer['ecomm_pagetype'] = 'product';
472
+ $dataLayer['ecomm_totalvalue'] = $eec_product_array[ 'price' ];
473
+
474
+ break;
475
+ }
476
+
477
+ case 'grouped': {
478
+ $dataLayer['productIsVariable'] = 0;
479
+
480
+ break;
481
+ }
482
+
483
+ default: {
484
+ $dataLayer['productIsVariable'] = 0;
485
+
486
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ] ) {
487
+ $dataLayer['ecomm_prodid'] = gtm4wp_prefix_productid( $eec_product_array[ 'id' ] );
488
+ $dataLayer['ecomm_pagetype'] = 'product';
489
+ $dataLayer['ecomm_totalvalue'] = $eec_product_array['price'];
490
+ }
491
+
492
+ if ( true === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) {
493
+ $currencyCode = get_woocommerce_currency();
494
+
495
+ $dataLayer['event'] = 'gtm4wp.changeDetailViewEEC';
496
+ $dataLayer['ecommerce'] = array(
497
+ 'currencyCode' => $currencyCode,
498
+ 'detail' => array(
499
+ 'products' => array(
500
+ $eec_product_array
501
+ )
502
+ )
503
+ );
504
+ }
505
+ }
506
+ }
507
+ }
508
+ } elseif ( is_cart() ) {
509
+ if (
510
+ $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ]
511
+ || $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEECCARTASFIRSTSTEP ]
512
+ || $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ]
513
+ ) {
514
+ $gtm4wp_cart_products = array();
515
+ $gtm4wp_cart_products_remarketing = array();
516
+
517
+ $gtm4wp_currency = get_woocommerce_currency();
518
+
519
+ foreach ( $woo->cart->get_cart() as $cart_item_id => $cart_item_data ) {
520
+ $product = apply_filters( 'woocommerce_cart_item_product', $cart_item_data['data'], $cart_item_data, $cart_item_id );
521
+
522
+ if ( ! apply_filters( GTM4WP_WPFILTER_EEC_CART_ITEM, true, $cart_item_data ) ) {
523
+ continue;
524
+ }
525
+
526
+ $eec_product_array = gtm4wp_process_product( $product, array(
527
+ 'quantity' => $cart_item_data['quantity']
528
+ ), 'cart' );
529
+
530
+ $gtm4wp_cart_products[] = $eec_product_array;
531
+ $gtm4wp_cart_products_remarketing[] = gtm4wp_prefix_productid( $eec_product_array[ 'id' ] );
532
+ }
533
+
534
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ] ) {
535
+ $dataLayer['ecomm_prodid'] = $gtm4wp_cart_products_remarketing;
536
+ $dataLayer['ecomm_pagetype'] = 'cart';
537
+ if ( ! $woo->cart->prices_include_tax ) {
538
+ $cart_total = $woo->cart->cart_contents_total;
539
+ } else {
540
+ $cart_total = $woo->cart->cart_contents_total + $woo->cart->tax_total;
541
+ }
542
+ $dataLayer['ecomm_totalvalue'] = (float) $cart_total;
543
+ }
544
+
545
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) {
546
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEECCARTASFIRSTSTEP ] ) {
547
+ $dataLayer['event'] = 'gtm4wp.checkoutStepEEC';
548
+ $dataLayer['ecommerce'] = array(
549
+ 'currencyCode' => $gtm4wp_currency,
550
+ 'checkout' => array(
551
+ 'actionField' => array(
552
+ 'step' => 1,
553
+ ),
554
+ 'products' => $gtm4wp_cart_products,
555
+ )
556
+ );
557
+ } else {
558
+ // add only ga4 products to populate view_cart event
559
+ $dataLayer['ecommerce'] = array(
560
+ 'cart' => $gtm4wp_cart_products
561
+ );
562
+ }
563
+ }
564
+ }
565
+ } elseif ( is_order_received_page() ) {
566
+ $do_not_flag_tracked_order = (bool) ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCNOORDERTRACKEDFLAG ] );
567
+ $order_id = empty( $_GET['order'] ) ? ( $GLOBALS['wp']->query_vars['order-received'] ? $GLOBALS['wp']->query_vars['order-received'] : 0 ) : absint( $_GET['order'] );
568
+ $order_id_filtered = apply_filters( 'woocommerce_thankyou_order_id', $order_id );
569
+ if ( '' != $order_id_filtered ) {
570
+ $order_id = $order_id_filtered;
571
+ }
572
+
573
+ $order_key = apply_filters( 'woocommerce_thankyou_order_key', empty( $_GET['key'] ) ? '' : wc_clean( $_GET['key'] ) );
574
+
575
+ if ( $order_id > 0 ) {
576
+ $order = wc_get_order( $order_id );
577
+
578
+ if ( $order instanceof WC_Order ) {
579
+ $this_order_key = $order->get_order_key();
580
+
581
+ if ( $this_order_key != $order_key ) {
582
+ unset( $order );
583
+ }
584
+ } else {
585
+ unset( $order );
586
+ }
587
+ }
588
+
589
+ // From this point if for any reason purchase data is not pushed
590
+ // that is because for a specific reason.
591
+ // In any other case woocommerce_thankyou hook will be the fallback if
592
+ // is_order_received_page does not work
593
+ // $GLOBALS['gtm4wp_woocommerce_purchase_data_pushed'] = true;
594
+
595
+ if(isset($order) && $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCORDERMAXAGE ] ){
596
+
597
+ $now = new DateTime();
598
+ if($order->is_paid() && $order->get_date_paid()){
599
+ $diff = $now->diff($order->get_date_paid());
600
+ $minutes = ($diff->days * 24 * 60) + ($diff->h * 60) + $diff->i;
601
+ } else {
602
+ $diff = $now->diff($order->get_date_created());
603
+ $minutes = ($diff->days * 24 * 60) + ($diff->h * 60) + $diff->i;
604
+ }
605
+
606
+ if($minutes > $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCORDERMAXAGE ]) {
607
+ unset($order);
608
+ }
609
+ }
610
+
611
+ $order_items = NULL;
612
+ if ( isset($order) && $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCORDERDATA ] ) {
613
+ $order_items = gtm4wp_process_order_items( $order );
614
+
615
+ $dataLayer['orderData'] = array(
616
+ 'attributes' => array(
617
+ 'date' => $order->get_date_created()->date( 'c' ),
618
+
619
+ 'order_number' => $order->get_order_number(),
620
+ 'order_key' => $order->get_order_key(),
621
+
622
+ 'payment_method' => esc_js( $order->get_payment_method() ),
623
+ 'payment_method_title' => esc_js( $order->get_payment_method_title() ),
624
+
625
+ 'shipping_method' => esc_js( $order->get_shipping_method() ),
626
+
627
+ 'status' => esc_js( $order->get_status() ),
628
+
629
+ 'coupons' => implode( ', ', ( $gtm4wp_is_woocommerce3_7 ? $order->get_coupon_codes() : $order->get_used_coupons() ) )
630
+ ),
631
+ 'totals' => array(
632
+ 'currency' => esc_js( $order->get_currency() ),
633
+ 'discount_total' => esc_js( $order->get_discount_total() ),
634
+ 'discount_tax' => esc_js( $order->get_discount_tax() ),
635
+ 'shipping_total' => esc_js( $order->get_shipping_total() ),
636
+ 'shipping_tax' => esc_js( $order->get_shipping_tax() ),
637
+ 'cart_tax' => esc_js( $order->get_cart_tax() ),
638
+ 'total' => esc_js( $order->get_total() ),
639
+ 'total_tax' => esc_js( $order->get_total_tax() ),
640
+ 'total_discount' => esc_js( $order->get_total_discount() ),
641
+ 'subtotal' => esc_js( $order->get_subtotal() ),
642
+ 'tax_totals' => $order->get_tax_totals()
643
+ ),
644
+ 'customer' => array(
645
+ 'id' => $order->get_customer_id(),
646
+
647
+ 'billing' => array(
648
+ 'first_name' => esc_js( $order->get_billing_first_name() ),
649
+ 'last_name' => esc_js( $order->get_billing_last_name() ),
650
+ 'company' => esc_js( $order->get_billing_company() ),
651
+ 'address_1' => esc_js( $order->get_billing_address_1() ),
652
+ 'address_2' => esc_js( $order->get_billing_address_2() ),
653
+ 'city' => esc_js( $order->get_billing_city() ),
654
+ 'state' => esc_js( $order->get_billing_state() ),
655
+ 'postcode' => esc_js( $order->get_billing_postcode() ),
656
+ 'country' => esc_js( $order->get_billing_country() ),
657
+ 'email' => esc_js( $order->get_billing_email() ),
658
+ 'emailhash' => esc_js( hash( 'sha256', $order->get_billing_email() ) ),
659
+ 'phone' => esc_js( $order->get_billing_phone() )
660
+ ),
661
+
662
+ 'shipping' => array(
663
+ 'first_name' => esc_js( $order->get_shipping_first_name() ),
664
+ 'last_name' => esc_js( $order->get_shipping_last_name() ),
665
+ 'company' => esc_js( $order->get_shipping_company() ),
666
+ 'address_1' => esc_js( $order->get_shipping_address_1() ),
667
+ 'address_2' => esc_js( $order->get_shipping_address_2() ),
668
+ 'city' => esc_js( $order->get_shipping_city() ),
669
+ 'state' => esc_js( $order->get_shipping_state() ),
670
+ 'postcode' => esc_js( $order->get_shipping_postcode() ),
671
+ 'country' => esc_js( $order->get_shipping_country() )
672
+ )
673
+
674
+ ),
675
+ 'items' => $order_items['products']
676
+ );
677
+ }
678
+
679
+ if ( ( 1 == get_post_meta( $order_id, '_ga_tracked', true ) ) && ! $do_not_flag_tracked_order ) {
680
+ unset( $order );
681
+ }
682
+
683
+ if ( isset( $_COOKIE[ 'gtm4wp_orderid_tracked' ] ) ) {
684
+ $tracked_order_id = filter_var( $_COOKIE[ 'gtm4wp_orderid_tracked' ], FILTER_VALIDATE_INT );
685
+
686
+ if ( $tracked_order_id && ( $tracked_order_id == $order_id ) && !$do_not_flag_tracked_order ) {
687
+ unset( $order );
688
+ }
689
+ }
690
+
691
+ if ( isset( $order ) ) {
692
+ $dataLayer = array_merge( $dataLayer, gtm4wp_get_purchase_datalayer( $order, $order_items ) );
693
+
694
+ if ( ! $do_not_flag_tracked_order ) {
695
+ update_post_meta( $order_id, '_ga_tracked', 1 );
696
+ }
697
+ }
698
+ } elseif ( is_checkout() ) {
699
+ if (
700
+ ( true === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] )
701
+ || ( true === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ] )
702
+ ) {
703
+ $gtm4wp_checkout_products = array();
704
+ $gtm4wp_checkout_products_remarketing = array();
705
+ $gtm4wp_totalvalue = 0;
706
+
707
+ foreach ( $woo->cart->get_cart() as $cart_item_id => $cart_item_data ) {
708
+ $product = apply_filters( 'woocommerce_cart_item_product', $cart_item_data['data'], $cart_item_data, $cart_item_id );
709
+
710
+ if ( ! apply_filters( GTM4WP_WPFILTER_EEC_CART_ITEM, true, $cart_item_data ) ) {
711
+ continue;
712
+ }
713
+
714
+ $eec_product_array = gtm4wp_process_product( $product, array(
715
+ 'quantity' => $cart_item_data['quantity']
716
+ ), 'cart' );
717
+
718
+ $gtm4wp_checkout_products[] = $eec_product_array;
719
+
720
+ $gtm4wp_checkout_products_remarketing[] = gtm4wp_prefix_productid( $eec_product_array[ 'id' ] );
721
+ $gtm4wp_totalvalue += $eec_product_array['quantity'] * $eec_product_array['price'];
722
+ } // end foreach cart item
723
+
724
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ] ) {
725
+ $dataLayer['ecomm_prodid'] = $gtm4wp_checkout_products_remarketing;
726
+ $dataLayer['ecomm_pagetype'] = 'cart';
727
+ $dataLayer['ecomm_totalvalue'] = (float) $gtm4wp_totalvalue;
728
+ }
729
+
730
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) {
731
+ $currencyCode = get_woocommerce_currency();
732
+
733
+ $ga4_products = array();
734
+ $sum_value = 0;
735
+ foreach( $gtm4wp_checkout_products as $oneproduct ) {
736
+ $ga4_products[] = gtm4wp_map_eec_to_ga4( $oneproduct );
737
+ $sum_value += $oneproduct["price"] * $oneproduct["quantity"];
738
+ }
739
+
740
+ $dataLayer['event'] = 'gtm4wp.checkoutStepEEC';
741
+ $dataLayer['ecommerce'] = array(
742
+ 'currencyCode' => $currencyCode,
743
+ 'checkout' => array(
744
+ 'actionField' => array(
745
+ 'step' => 1 + (int) $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEECCARTASFIRSTSTEP ],
746
+ ),
747
+ 'products' => $gtm4wp_checkout_products,
748
+ )
749
+ );
750
+
751
+ wc_enqueue_js('
752
+ window.gtm4wp_checkout_products = ' . json_encode( $gtm4wp_checkout_products ) . ';
753
+ window.gtm4wp_checkout_products_ga4 = ' . json_encode( $ga4_products ) . ';
754
+ window.gtm4wp_checkout_value = ' . (float) $sum_value . ';
755
+ window.gtm4wp_checkout_step_offset = ' . (int) $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCEECCARTASFIRSTSTEP ] . ';'
756
+ );
757
+ }
758
+ }
759
+ } else {
760
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ] ) {
761
+ $dataLayer['ecomm_pagetype'] = 'other';
762
+ }
763
+ }
764
+
765
+ if ( function_exists( 'WC' ) && WC()->session ) {
766
+ $cart_readded_hash = WC()->session->get( 'gtm4wp_product_readded_to_cart' );
767
+ if ( isset( $cart_readded_hash ) ) {
768
+ $cart_item = $woo->cart->get_cart_item( $cart_readded_hash );
769
+ if ( ! empty( $cart_item ) ) {
770
+ $product = $cart_item['data'];
771
+
772
+ $eec_product_array = gtm4wp_process_product( $product, array(
773
+ 'quantity' => $cart_item['quantity']
774
+ ), 'readdedtocart' );
775
+
776
+ $currencyCode = get_woocommerce_currency();
777
+
778
+ $dataLayer['event'] = 'gtm4wp.addProductToCartEEC';
779
+ $dataLayer['ecommerce'] = array(
780
+ 'currencyCode' => $currencyCode,
781
+ 'add' => array(
782
+ 'products' => array(
783
+ $eec_product_array
784
+ )
785
+ )
786
+ );
787
+ }
788
+
789
+ WC()->session->set( 'gtm4wp_product_readded_to_cart', NULL );
790
+ }
791
+ }
792
+
793
+ return $dataLayer;
794
+ }
795
+
796
+ function gtm4wp_woocommerce_thankyou( $order_id ) {
797
+ global $gtm4wp_options, $gtm4wp_datalayer_name;
798
+
799
+ // if this flag is set to true, it means that the puchase event was fired
800
+ // when capturing the is_order_received_page template tag therefore
801
+ // no need to handle this here twice
802
+ if ( $GLOBALS['gtm4wp_woocommerce_purchase_data_pushed'] ) {
803
+ return;
804
+ }
805
+
806
+ if ( $order_id > 0 ) {
807
+ $order = wc_get_order( $order_id );
808
+ }
809
+
810
+ if( isset( $order ) && $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCORDERMAXAGE ] ) {
811
+ $now = new DateTime();
812
+ if( $order->is_paid() && $order->get_date_paid() ) {
813
+ $diff = $now->diff( $order->get_date_paid() );
814
+ $minutes = ( $diff->days * 24 * 60 ) + ( $diff->h * 60 ) + $diff->i;
815
+ } else {
816
+ $diff = $now->diff( $order->get_date_created() );
817
+ $minutes = ( $diff->days * 24 * 60 ) + ( $diff->h * 60 ) + $diff->i;
818
+ }
819
+
820
+ if( $minutes > $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCORDERMAXAGE ] ) {
821
+ unset( $order );
822
+ }
823
+ }
824
+
825
+ $do_not_flag_tracked_order = (bool) ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCNOORDERTRACKEDFLAG ] );
826
+ if ( ( 1 == get_post_meta( $order_id, '_ga_tracked', true ) ) && ! $do_not_flag_tracked_order ) {
827
+ unset( $order );
828
+ }
829
+
830
+ if ( isset( $_COOKIE[ 'gtm4wp_orderid_tracked' ] ) ) {
831
+ $tracked_order_id = filter_var( $_COOKIE[ 'gtm4wp_orderid_tracked' ], FILTER_VALIDATE_INT );
832
+
833
+ if ( $tracked_order_id && ( $tracked_order_id == $order_id ) && !$do_not_flag_tracked_order ) {
834
+ unset( $order );
835
+ }
836
+ }
837
+
838
+ if ( isset( $order ) ) {
839
+ $dataLayer = gtm4wp_get_purchase_datalayer( $order, NULL );
840
+
841
+ $has_html5_support = current_theme_supports( 'html5' );
842
+
843
+ echo '
844
+ <script data-cfasync="false" data-pagespeed-no-defer' . ( $has_html5_support ? ' type="text/javascript"' : '' ) . '>//<![CDATA[
845
+ window.' . $gtm4wp_datalayer_name . ' = window.' . $gtm4wp_datalayer_name . ' || [];
846
+ window.' . $gtm4wp_datalayer_name . '.push(' . json_encode( $dataLayer ) . ');
847
+ //]]></script>';
848
+
849
+ if ( ! $do_not_flag_tracked_order ) {
850
+ update_post_meta( $order_id, '_ga_tracked', 1 );
851
+ }
852
+ }
853
+ }
854
+
855
+ function gtm4wp_woocommerce_single_add_to_cart_tracking() {
856
+ global $product, $gtm4wp_datalayer_name, $gtm4wp_options;
857
+
858
+ // exit early if there is nothing to do
859
+ if ( ( false === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKCLASSICEC ] ) && ( false === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) ) {
860
+ return;
861
+ }
862
+
863
+ $eec_product_array = gtm4wp_process_product( $product, array(), 'addtocartsingle' );
864
+
865
+ foreach ( $eec_product_array as $eec_product_array_key => $eec_product_array_value ) {
866
+ echo '<input type="hidden" name="gtm4wp_' . esc_attr( $eec_product_array_key ) . '" value="' . esc_attr( $eec_product_array_value ) . '" />' . "\n";
867
+ }
868
+ }
869
+
870
+ $GLOBALS['gtm4wp_cart_item_proddata'] = '';
871
+ function gtm4wp_woocommerce_cart_item_product_filter( $product, $cart_item = '', $cart_id = '' ) {
872
+ global $gtm4wp_options;
873
+
874
+ $eec_product_array = gtm4wp_process_product( $product, array(
875
+ 'productlink' => apply_filters( 'the_permalink', get_permalink(), 0 )
876
+ ), 'cart' );
877
+
878
+ $GLOBALS['gtm4wp_cart_item_proddata'] = $eec_product_array;
879
+
880
+ return $product;
881
+ }
882
+
883
+ function gtm4wp_woocommerce_cart_item_remove_link_filter( $remove_from_cart_link ) {
884
+ if ( ! isset( $GLOBALS['gtm4wp_cart_item_proddata'] ) ) {
885
+ return $remove_from_cart_link;
886
+ }
887
+
888
+ if ( ! is_array( $GLOBALS['gtm4wp_cart_item_proddata'] ) ) {
889
+ return $remove_from_cart_link;
890
+ }
891
+
892
+ if ( ! isset( $GLOBALS['gtm4wp_cart_item_proddata']['variant'] ) ) {
893
+ $GLOBALS['gtm4wp_cart_item_proddata']['variant'] = '';
894
+ }
895
+
896
+ if ( ! isset( $GLOBALS['gtm4wp_cart_item_proddata']['brand'] ) ) {
897
+ $GLOBALS['gtm4wp_cart_item_proddata']['brand'] = '';
898
+ }
899
+
900
+ $cartlink_with_data = sprintf(
901
+ 'data-gtm4wp_product_id="%s" data-gtm4wp_product_name="%s" data-gtm4wp_product_price="%s" data-gtm4wp_product_cat="%s" data-gtm4wp_product_url="%s" data-gtm4wp_product_variant="%s" data-gtm4wp_product_stocklevel="%s" data-gtm4wp_product_brand="%s" href="',
902
+ esc_attr( $GLOBALS['gtm4wp_cart_item_proddata']['id'] ),
903
+ esc_attr( $GLOBALS['gtm4wp_cart_item_proddata']['name'] ),
904
+ esc_attr( $GLOBALS['gtm4wp_cart_item_proddata']['price'] ),
905
+ esc_attr( $GLOBALS['gtm4wp_cart_item_proddata']['category'] ),
906
+ esc_url( $GLOBALS['gtm4wp_cart_item_proddata']['productlink'] ),
907
+ esc_attr( $GLOBALS['gtm4wp_cart_item_proddata']['variant'] ),
908
+ esc_attr( $GLOBALS['gtm4wp_cart_item_proddata']['stocklevel'] ),
909
+ esc_attr( $GLOBALS['gtm4wp_cart_item_proddata']['brand'] )
910
+ );
911
+ $GLOBALS['gtm4wp_cart_item_proddata'] = '';
912
+
913
+ return gtm4wp_str_replace_first( 'href="', $cartlink_with_data, $remove_from_cart_link );
914
+ }
915
+
916
+ function gtp4wp_woocommerce_reset_loop() {
917
+ global $woocommerce_loop;
918
+
919
+ $woocommerce_loop['listtype'] = '';
920
+ }
921
+
922
+ function gtm4wp_woocommerce_add_related_to_loop( $arg ) {
923
+ global $woocommerce_loop;
924
+
925
+ $woocommerce_loop['listtype'] = __( 'Related Products', 'duracelltomi-google-tag-manager' );
926
+
927
+ return $arg;
928
+ }
929
+
930
+ function gtm4wp_woocommerce_add_cross_sell_to_loop( $arg ) {
931
+ global $woocommerce_loop;
932
+
933
+ $woocommerce_loop['listtype'] = __( 'Cross-Sell Products', 'duracelltomi-google-tag-manager' );
934
+
935
+ return $arg;
936
+ }
937
+
938
+ function gtm4wp_woocommerce_add_upsells_to_loop( $arg ) {
939
+ global $woocommerce_loop;
940
+
941
+ $woocommerce_loop['listtype'] = __( 'Upsell Products', 'duracelltomi-google-tag-manager' );
942
+
943
+ return $arg;
944
+ }
945
+
946
+ function gtm4wp_woocommerce_before_template_part( $template_name ) {
947
+ ob_start();
948
+ }
949
+
950
+ function gtm4wp_woocommerce_after_template_part( $template_name ) {
951
+ global $product, $gtm4wp_product_counter, $gtm4wp_last_widget_title, $gtm4wp_options;
952
+
953
+ $productitem = ob_get_contents();
954
+ ob_end_clean();
955
+
956
+ if ( 'content-widget-product.php' == $template_name ) {
957
+ $eec_product_array = gtm4wp_process_product( $product, array(
958
+ 'productlink' => apply_filters( 'the_permalink', get_permalink(), 0 ),
959
+ 'listname' => $gtm4wp_last_widget_title,
960
+ 'listposition' => $gtm4wp_product_counter
961
+ ), 'widgetproduct' );
962
+
963
+ if ( ! isset( $eec_product_array[ 'brand' ] ) ) {
964
+ $eec_product_array[ 'brand' ] = '';
965
+ }
966
+
967
+ $productlink_with_data = sprintf(
968
+ 'data-gtm4wp_product_id="%s" data-gtm4wp_product_name="%s" data-gtm4wp_product_price="%s" data-gtm4wp_product_cat="%s" data-gtm4wp_product_url="%s" data-gtm4wp_productlist_name="%s" data-gtm4wp_product_listposition="%s" data-gtm4wp_product_stocklevel="%s" data-gtm4wp_product_brand="%s" href="',
969
+ esc_attr( $eec_product_array['id'] ),
970
+ esc_attr( $eec_product_array['name'] ),
971
+ esc_attr( $eec_product_array['price'] ),
972
+ esc_attr( $eec_product_array['category'] ),
973
+ esc_url( $eec_product_array['productlink'] ),
974
+ esc_attr( $eec_product_array['listname'] ),
975
+ esc_attr( $eec_product_array['listposition'] ),
976
+ esc_attr( $eec_product_array['stocklevel'] ),
977
+ esc_attr( $eec_product_array[ "brand" ] )
978
+ );
979
+
980
+ $gtm4wp_product_counter++;
981
+
982
+ $productitem = str_replace( 'href="', $productlink_with_data, $productitem );
983
+ }
984
+
985
+ echo $productitem;
986
+ }
987
+
988
+ function gtm4wp_widget_title_filter( $widget_title ) {
989
+ global $gtm4wp_product_counter, $gtm4wp_last_widget_title;
990
+
991
+ $gtm4wp_product_counter = 1;
992
+ $gtm4wp_last_widget_title = $widget_title . __( ' (widget)', 'duracelltomi-google-tag-manager' );
993
+
994
+ return $widget_title;
995
+ }
996
+
997
+ function gtm4wp_before_recent_products_loop() {
998
+ global $woocommerce_loop;
999
+
1000
+ $woocommerce_loop['listtype'] = __( 'Recent Products', 'duracelltomi-google-tag-manager' );
1001
+ }
1002
+
1003
+ function gtm4wp_before_sale_products_loop() {
1004
+ global $woocommerce_loop;
1005
+
1006
+ $woocommerce_loop['listtype'] = __( 'Sale Products', 'duracelltomi-google-tag-manager' );
1007
+ }
1008
+
1009
+ function gtm4wp_before_best_selling_products_loop() {
1010
+ global $woocommerce_loop;
1011
+
1012
+ $woocommerce_loop['listtype'] = __( 'Best Selling Products', 'duracelltomi-google-tag-manager' );
1013
+ }
1014
+
1015
+ function gtm4wp_before_top_rated_products_loop() {
1016
+ global $woocommerce_loop;
1017
+
1018
+ $woocommerce_loop['listtype'] = __( 'Top Rated Products', 'duracelltomi-google-tag-manager' );
1019
+ }
1020
+
1021
+ function gtm4wp_before_featured_products_loop() {
1022
+ global $woocommerce_loop;
1023
+
1024
+ $woocommerce_loop['listtype'] = __( 'Featured Products', 'duracelltomi-google-tag-manager' );
1025
+ }
1026
+
1027
+ function gtm4wp_before_related_products_loop() {
1028
+ global $woocommerce_loop;
1029
+
1030
+ $woocommerce_loop['listtype'] = __( 'Related Products', 'duracelltomi-google-tag-manager' );
1031
+ }
1032
+
1033
+ function gtm4wp_woocommerce_get_product_list_item_extra_tag($product, $listtype, $itemix, $permalink) {
1034
+ global $wp_query, $gtm4wp_options;
1035
+
1036
+ if ( ! isset( $product ) ) {
1037
+ return;
1038
+ }
1039
+
1040
+ $product_id = $product->get_id();
1041
+
1042
+ $product_cat = '';
1043
+ if ( is_product_category() ) {
1044
+ global $wp_query;
1045
+ $cat_obj = $wp_query->get_queried_object();
1046
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCUSEFULLCATEGORYPATH ] ) {
1047
+ $product_cat = gtm4wp_get_product_category_hierarchy( $cat_obj->term_id );
1048
+ } else {
1049
+ $product_cat = $cat_obj->name;
1050
+ }
1051
+ } else {
1052
+ $product_cat = gtm4wp_get_product_category( $product_id, $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCUSEFULLCATEGORYPATH ] );
1053
+ }
1054
+
1055
+ if ( is_search() ) {
1056
+ $list_name = __( 'Search Results', 'duracelltomi-google-tag-manager' );
1057
+ } elseif ( $listtype != '' ) {
1058
+ $list_name = $listtype;
1059
+ } else {
1060
+ $list_name = __( 'General Product List', 'duracelltomi-google-tag-manager' );
1061
+ }
1062
+
1063
+ $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
1064
+ $posts_per_page = get_query_var( 'posts_per_page' );
1065
+ if ( $posts_per_page < 1 ) {
1066
+ $posts_per_page = 1;
1067
+ }
1068
+
1069
+ $eec_product_array = gtm4wp_process_product( $product, array(
1070
+ 'productlink' => $permalink,
1071
+ 'listname' => $list_name,
1072
+ 'listposition' => $itemix + ( $posts_per_page * ( $paged - 1 ) )
1073
+ ), 'productlist' );
1074
+
1075
+ if ( ! isset( $eec_product_array[ 'brand' ] ) ) {
1076
+ $eec_product_array[ 'brand' ] = '';
1077
+ }
1078
+
1079
+ return sprintf(
1080
+ '<span class="gtm4wp_productdata" style="display:none; visibility:hidden;" data-gtm4wp_product_id="%s" data-gtm4wp_product_name="%s" data-gtm4wp_product_price="%s" data-gtm4wp_product_cat="%s" data-gtm4wp_product_url="%s" data-gtm4wp_product_listposition="%s" data-gtm4wp_productlist_name="%s" data-gtm4wp_product_stocklevel="%s" data-gtm4wp_product_brand="%s"></span>',
1081
+ esc_attr( $eec_product_array['id'] ),
1082
+ esc_attr( $eec_product_array['name'] ),
1083
+ esc_attr( $eec_product_array['price'] ),
1084
+ esc_attr( $eec_product_array['category'] ),
1085
+ esc_url( $eec_product_array['productlink'] ),
1086
+ esc_attr( $eec_product_array['listposition'] ),
1087
+ esc_attr( $eec_product_array['listname'] ),
1088
+ esc_attr( $eec_product_array['stocklevel'] ),
1089
+ esc_attr( $eec_product_array[ "brand" ] )
1090
+ );
1091
+ }
1092
+
1093
+ function gtm4wp_woocommerce_after_shop_loop_item() {
1094
+ global $product, $woocommerce_loop;
1095
+
1096
+ $listtype = "";
1097
+ if ( isset( $woocommerce_loop['listtype'] ) && ( $woocommerce_loop['listtype'] != '' ) ) {
1098
+ $listtype = $woocommerce_loop['listtype'];
1099
+ }
1100
+
1101
+ $itemix = "";
1102
+ if ( isset( $woocommerce_loop['loop'] ) && ( $woocommerce_loop['loop'] != '' ) ) {
1103
+ $itemix = $woocommerce_loop['loop'];
1104
+ }
1105
+
1106
+ echo gtm4wp_woocommerce_get_product_list_item_extra_tag($product, $listtype, $itemix, apply_filters( 'the_permalink', get_permalink(), 0 ));
1107
+ }
1108
+
1109
+ function gtm4wp_woocommerce_cart_item_restored( $cart_item_key ) {
1110
+ if ( function_exists( 'WC' ) && WC()->session ) {
1111
+ WC()->session->set( 'gtm4wp_product_readded_to_cart', $cart_item_key );
1112
+ }
1113
+ }
1114
+
1115
+ function gtm4wp_woocommerce_enqueue_scripts() {
1116
+ global $gtm4wp_options, $gtp4wp_plugin_url;
1117
+
1118
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKCLASSICEC ] ) {
1119
+ $in_footer = apply_filters( 'gtm4wp_' . GTM4WP_OPTION_INTEGRATE_WCTRACKCLASSICEC, false );
1120
+ wp_enqueue_script( 'gtm4wp-woocommerce-classic', $gtp4wp_plugin_url . 'js/gtm4wp-woocommerce-classic.js', array( 'jquery' ), GTM4WP_VERSION, $in_footer );
1121
+ }
1122
+
1123
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) {
1124
+ $in_footer = apply_filters( 'gtm4wp_' . GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC, false );
1125
+ wp_enqueue_script( 'gtm4wp-woocommerce-enhanced', $gtp4wp_plugin_url . 'js/gtm4wp-woocommerce-enhanced.js', array( 'jquery' ), GTM4WP_VERSION, $in_footer );
1126
+ }
1127
+ }
1128
+
1129
+ function gtm4wp_wc_quick_view_before_single_product() {
1130
+ global $gtm4wp_options, $gtm4wp_datalayer_name;
1131
+
1132
+ $dataLayer = array(
1133
+ 'event' => 'gtm4wp.changeDetailViewEEC',
1134
+ );
1135
+
1136
+ if ( ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ] ) || ( true === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) ) {
1137
+ $postid = get_the_ID();
1138
+ $product = wc_get_product( $postid );
1139
+
1140
+ $eec_product_array = gtm4wp_process_product( $product, array(), 'productdetail' );
1141
+
1142
+ $dataLayer['productRatingCounts'] = $product->get_rating_counts();
1143
+ $dataLayer['productAverageRating'] = (float) $product->get_average_rating();
1144
+ $dataLayer['productReviewCount'] = (int) $product->get_review_count();
1145
+ $dataLayer['productType'] = $product->get_type();
1146
+
1147
+ switch ( $dataLayer['productType'] ) {
1148
+ case 'variable': {
1149
+ $dataLayer['productIsVariable'] = 1;
1150
+
1151
+ $dataLayer['ecomm_prodid'] = gtm4wp_prefix_productid( $eec_product_array[ 'id' ] );
1152
+ $dataLayer['ecomm_pagetype'] = 'product';
1153
+ $dataLayer['ecomm_totalvalue'] = $eec_product_array[ 'price' ];
1154
+
1155
+ break;
1156
+ }
1157
+
1158
+ case 'grouped': {
1159
+ $dataLayer['productIsVariable'] = 0;
1160
+
1161
+ break;
1162
+ }
1163
+
1164
+ default: {
1165
+ $dataLayer['productIsVariable'] = 0;
1166
+
1167
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCREMARKETING ] ) {
1168
+ $dataLayer['ecomm_prodid'] = gtm4wp_prefix_productid( $eec_product_array[ 'id' ] );
1169
+ $dataLayer['ecomm_pagetype'] = 'product';
1170
+ $dataLayer['ecomm_totalvalue'] = $eec_product_array['price'];
1171
+ }
1172
+
1173
+ if ( true === $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) {
1174
+ $currencyCode = get_woocommerce_currency();
1175
+
1176
+ $dataLayer['ecommerce'] = array(
1177
+ 'currencyCode' => $currencyCode,
1178
+ 'detail' => array(
1179
+ 'products' => array(
1180
+ $eec_product_array
1181
+ )
1182
+ )
1183
+ );
1184
+ }
1185
+ }
1186
+ }
1187
+ }
1188
+
1189
+ echo '
1190
+ <span style="display: none;" id="gtm4wp_quickview_data" data-gtm4wp_datalayer="' . esc_attr(json_encode( $dataLayer )) . '"></span>';
1191
+ }
1192
+
1193
+ function gtm4wp_woocommerce_grouped_product_list_column_label( $labelvalue, $product ) {
1194
+ global $gtm4wp_options, $gtm4wp_grouped_product_ix;
1195
+
1196
+ if ( ! isset( $product ) ) {
1197
+ return $labelvalue;
1198
+ }
1199
+
1200
+ $list_name = __( 'Grouped Product Detail Page', 'duracelltomi-google-tag-manager' );
1201
+
1202
+ $eec_product_array = gtm4wp_process_product( $product, array(
1203
+ 'productlink' => $product->get_permalink(),
1204
+ 'listname' => $list_name,
1205
+ 'listposition' => $gtm4wp_grouped_product_ix
1206
+ ), 'groupedproductlist' );
1207
+
1208
+ $gtm4wp_grouped_product_ix++;
1209
+
1210
+ if ( ! isset( $eec_product_array[ 'brand' ] ) ) {
1211
+ $eec_product_array[ 'brand' ] = '';
1212
+ }
1213
+
1214
+ $labelvalue .=
1215
+ sprintf(
1216
+ '<span class="gtm4wp_productdata" style="display:none; visibility:hidden;" data-gtm4wp_product_id="%s" data-gtm4wp_product_sku="%s" data-gtm4wp_product_name="%s" data-gtm4wp_product_price="%s" data-gtm4wp_product_cat="%s" data-gtm4wp_product_url="%s" data-gtm4wp_product_listposition="%s" data-gtm4wp_productlist_name="%s" data-gtm4wp_product_stocklevel="%s" data-gtm4wp_product_brand="%s"></span>',
1217
+ esc_attr( $eec_product_array['id'] ),
1218
+ esc_attr( $eec_product_array['sku'] ),
1219
+ esc_attr( $eec_product_array['name'] ),
1220
+ esc_attr( $eec_product_array['price'] ),
1221
+ esc_attr( $eec_product_array['category'] ),
1222
+ esc_url( $eec_product_array['productlink'] ),
1223
+ esc_attr( $eec_product_array['listposition'] ),
1224
+ esc_attr( $eec_product_array['listname'] ),
1225
+ esc_attr( $eec_product_array['stocklevel'] ),
1226
+ esc_attr( $eec_product_array['brand'] )
1227
+ );
1228
+
1229
+ return $labelvalue;
1230
+ }
1231
+
1232
+ function gtm4wp_add_productdata_to_wc_block($content, $data, $product) {
1233
+ $product_data_tag = gtm4wp_woocommerce_get_product_list_item_extra_tag($product, "", 0, $data->permalink);
1234
+
1235
+ return preg_replace('/<li.+class=("|"[^"]+)wc-block-grid__product("|[^"]+")[^<]*>/i', '$0' . $product_data_tag, $content);
1236
+ }
1237
+
1238
+ function gtm4wp_woocommerce_header_top() {
1239
+ $has_html5_support = current_theme_supports( 'html5' );
1240
+
1241
+ echo "<script" . ( $has_html5_support ? ' type="text/javascript"' : '' ) . ">
1242
+ const gtm4wp_is_safari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
1243
+ if ( gtm4wp_is_safari ) {
1244
+ window.addEventListener('pageshow', function(event) {
1245
+ if ( event.persisted ) {
1246
+ // if Safari loads the page from cache usually by navigating with the back button
1247
+ // it creates issues with product list click tracking
1248
+ // therefore GTM4WP forces the page reload in this browser
1249
+ window.location.reload();
1250
+ }
1251
+ });
1252
+ }
1253
+ </script>";
1254
+ }
1255
+
1256
+ // do not add filter if someone enabled WooCommerce integration without an activated WooCommerce plugin
1257
+ if ( function_exists( 'WC' ) ) {
1258
+ add_filter( GTM4WP_WPFILTER_COMPILE_DATALAYER, 'gtm4wp_woocommerce_datalayer_filter_items' );
1259
+
1260
+ add_filter( 'loop_end', 'gtp4wp_woocommerce_reset_loop' );
1261
+ add_action( 'woocommerce_after_shop_loop_item', 'gtm4wp_woocommerce_after_shop_loop_item' );
1262
+ add_action( 'woocommerce_after_add_to_cart_button', 'gtm4wp_woocommerce_single_add_to_cart_tracking' );
1263
+
1264
+ // add_action( "wp_footer", "gtm4wp_woocommerce_wp_footer" );
1265
+ add_action( 'wp_enqueue_scripts', 'gtm4wp_woocommerce_enqueue_scripts' );
1266
+ add_filter( GTM4WP_WPFILTER_ADDGLOBALVARS, 'gtm4wp_woocommerce_addglobalvars' );
1267
+
1268
+ add_filter( 'woocommerce_blocks_product_grid_item_html', 'gtm4wp_add_productdata_to_wc_block', 10, 3);
1269
+
1270
+ add_action( 'woocommerce_thankyou', 'gtm4wp_woocommerce_thankyou' );
1271
+
1272
+ if ( true === $GLOBALS['gtm4wp_options'][ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) {
1273
+ add_action( 'woocommerce_before_template_part', 'gtm4wp_woocommerce_before_template_part' );
1274
+ add_action( 'woocommerce_after_template_part', 'gtm4wp_woocommerce_after_template_part' );
1275
+ add_filter( 'widget_title', 'gtm4wp_widget_title_filter' );
1276
+ add_action( 'wc_quick_view_before_single_product', 'gtm4wp_wc_quick_view_before_single_product' );
1277
+ add_filter( 'woocommerce_grouped_product_list_column_label', 'gtm4wp_woocommerce_grouped_product_list_column_label', 10, 2 );
1278
+
1279
+ add_filter( 'woocommerce_cart_item_product', 'gtm4wp_woocommerce_cart_item_product_filter' );
1280
+ add_filter( 'woocommerce_cart_item_remove_link', 'gtm4wp_woocommerce_cart_item_remove_link_filter' );
1281
+ add_action( 'woocommerce_cart_item_restored', 'gtm4wp_woocommerce_cart_item_restored' );
1282
+
1283
+ add_filter( 'woocommerce_related_products_args', 'gtm4wp_woocommerce_add_related_to_loop' );
1284
+ add_filter( 'woocommerce_related_products_columns', 'gtm4wp_woocommerce_add_related_to_loop' );
1285
+ add_filter( 'woocommerce_cross_sells_columns', 'gtm4wp_woocommerce_add_cross_sell_to_loop' );
1286
+ add_filter( 'woocommerce_upsells_columns', 'gtm4wp_woocommerce_add_upsells_to_loop' );
1287
+
1288
+ add_action( 'woocommerce_shortcode_before_recent_products_loop', 'gtm4wp_before_recent_products_loop' );
1289
+ add_action( 'woocommerce_shortcode_before_sale_products_loop', 'gtm4wp_before_sale_products_loop' );
1290
+ add_action( 'woocommerce_shortcode_before_best_selling_products_loop', 'gtm4wp_before_best_selling_products_loop' );
1291
+ add_action( 'woocommerce_shortcode_before_top_rated_products_loop', 'gtm4wp_before_top_rated_products_loop' );
1292
+ add_action( 'woocommerce_shortcode_before_featured_products_loop', 'gtm4wp_before_featured_products_loop' );
1293
+ add_action( 'woocommerce_shortcode_before_related_products_loop', 'gtm4wp_before_related_products_loop' );
1294
+
1295
+ add_action( 'wp_head', 'gtm4wp_woocommerce_header_top', 1, 0 );
1296
+ }
1297
+ }
integration/youtube.php CHANGED
@@ -1,18 +1,18 @@
1
- <?php
2
- function gtm4wp_youtube( $return, $url, $data ) {
3
- $site_url = site_url();
4
- $site_url_parts = parse_url( $site_url );
5
-
6
- if ( false !== strpos( $return, 'youtube.com' ) ) {
7
- return str_replace( 'feature=oembed', 'feature=oembed&enablejsapi=1&origin=' . $site_url_parts['scheme'] . '://' . $site_url_parts['host'], $return );
8
- } else {
9
- return $return;
10
- }
11
- }
12
-
13
- add_filter( 'oembed_result', 'gtm4wp_youtube', 10, 3 );
14
-
15
- if ( ! is_admin() ) {
16
- $in_footer = apply_filters( 'gtm4wp_youtube', false );
17
- wp_enqueue_script( 'gtm4wp-youtube', $gtp4wp_plugin_url . 'js/gtm4wp-youtube.js', array( 'jquery' ), GTM4WP_VERSION, $in_footer );
18
- }
1
+ <?php
2
+ function gtm4wp_youtube( $return, $url, $data ) {
3
+ $site_url = site_url();
4
+ $site_url_parts = parse_url( $site_url );
5
+
6
+ if ( false !== strpos( $return, 'youtube.com' ) ) {
7
+ return str_replace( 'feature=oembed', 'feature=oembed&enablejsapi=1&origin=' . $site_url_parts['scheme'] . '://' . $site_url_parts['host'], $return );
8
+ } else {
9
+ return $return;
10
+ }
11
+ }
12
+
13
+ add_filter( 'oembed_result', 'gtm4wp_youtube', 10, 3 );
14
+
15
+ if ( ! is_admin() ) {
16
+ $in_footer = apply_filters( 'gtm4wp_youtube', true );
17
+ wp_enqueue_script( 'gtm4wp-youtube', $gtp4wp_plugin_url . 'js/gtm4wp-youtube.js', array(), GTM4WP_VERSION, $in_footer );
18
+ }
js/gtm4wp-contact-form-7-tracker.js CHANGED
@@ -1,24 +1,17 @@
1
- jQuery( function() {
2
- jQuery( ".wpcf7" )
3
- .on( 'wpcf7mailsent', function( e ) {
4
- var gtm4wp_cf7formid = '(not set)';
5
- if ( e && e.detail && e.detail.contactFormId ) {
6
- gtm4wp_cf7formid = e.detail.contactFormId;
7
- } else if ( e && e.originalEvent && e.originalEvent.detail && e.originalEvent.detail.contactFormId ) {
8
- gtm4wp_cf7formid = e.originalEvent.detail.contactFormId;
9
- }
10
 
11
- var gtm4wp_cf7forminputs = [];
12
- if ( e && e.detail && e.detail.inputs ) {
13
- gtm4wp_cf7forminputs = e.detail.inputs;
14
- } else if ( e && e.originalEvent && e.originalEvent.detail && e.originalEvent.detail.inputs ) {
15
- gtm4wp_cf7forminputs = e.originalEvent.detail.inputs;
16
- }
17
 
18
- window[ gtm4wp_datalayer_name ].push({
19
- 'event': 'gtm4wp.contactForm7Submitted',
20
- 'gtm4wp.cf7formid': gtm4wp_cf7formid,
21
- 'gtm4wp.cf7inputs': gtm4wp_cf7forminputs
22
- });
23
- });
24
  });
1
+ document.addEventListener('wpcf7submit', function(event) {
2
+ let gtm4wp_cf7formid = '(not set)';
3
+ if ( event && event.detail && event.detail.contactFormId ) {
4
+ gtm4wp_cf7formid = event.detail.contactFormId;
5
+ }
 
 
 
 
6
 
7
+ let gtm4wp_cf7forminputs = [];
8
+ if ( event && event.detail && event.detail.inputs ) {
9
+ gtm4wp_cf7forminputs = event.detail.inputs;
10
+ }
 
 
11
 
12
+ window[ gtm4wp_datalayer_name ].push({
13
+ 'event': 'gtm4wp.contactForm7Submitted',
14
+ 'gtm4wp.cf7formid': gtm4wp_cf7formid,
15
+ 'gtm4wp.cf7inputs': gtm4wp_cf7forminputs
16
+ });
 
17
  });
js/gtm4wp-form-move-tracker.js CHANGED
@@ -1,50 +1,33 @@
1
- jQuery( function() {
2
- jQuery( ":input" )
3
- .on( "focus", function() {
4
- var input = jQuery(this);
5
- var inputID = input.attr("id") || "(no input ID)";
6
- var inputName = input.attr("name") || "(no input name)";
7
- var inputClass = input.attr("class") || "(no input class)";
8
-
9
- var form = jQuery(this.form);
10
- var formID = form.attr("id") || "(no form ID)";
11
- var formName = form.attr("name") || "(no form name)";
12
- var formClass = form.attr("class") || "(no form class)";
13
-
14
- window[ gtm4wp_datalayer_name ].push({
15
- 'event' : 'gtm4wp.formElementEnter',
16
-
17
- 'inputID' : inputID,
18
- 'inputName' : inputName,
19
- 'inputClass': inputClass,
20
-
21
- 'formID' : formID,
22
- 'formName' : formName,
23
- 'formClass': formClass
24
- });
25
- })
26
-
27
- .on( "blur", function() {
28
- var input = jQuery(this);
29
- var inputID = input.attr("id") || "(no input ID)";
30
- var inputName = input.attr("name") || "(no input name)";
31
- var inputClass = input.attr("class") || "(no input class)";
32
-
33
- var form = jQuery(this.form);
34
- var formID = form.attr("id") || "(no form ID)";
35
- var formName = form.attr("name") || "(no form name)";
36
- var formClass = form.attr("class") || "(no form class)";
37
-
38
- window[ gtm4wp_datalayer_name ].push({
39
- 'event' : 'gtm4wp.formElementLeave',
40
-
41
- 'inputID' : inputID,
42
- 'inputName' : inputName,
43
- 'inputClass': inputClass,
44
-
45
- 'formID' : formID,
46
- 'formName' : formName,
47
- 'formClass': formClass
48
- });
49
  });
50
- });
 
1
+ document.addEventListener("focusin", function(event) {
2
+ const elem = event.target.closest("input,select,textarea,button,meter,progress");
3
+ if ( elem ) {
4
+ window[ gtm4wp_datalayer_name ].push({
5
+ 'event' : 'gtm4wp.formElementEnter',
6
+
7
+ 'inputID' : elem.getAttribute("id") || "(no input ID)",
8
+ 'inputName' : elem.getAttribute("name") || "(no input name)",
9
+ 'inputClass': elem.getAttribute("class") || "(no input class)",
10
+
11
+ 'formID' : elem.form.getAttribute("id") || "(no form ID)",
12
+ 'formName' : elem.form.getAttribute("name") || "(no form name)",
13
+ 'formClass': elem.form.getAttribute("class") || "(no form class)"
14
+ });
15
+ }
16
+ }, false);
17
+
18
+ document.addEventListener("focusout", function(event) {
19
+ const elem = event.target.closest("input,select,textarea,button,meter,progress");
20
+ if ( elem ) {
21
+ window[ gtm4wp_datalayer_name ].push({
22
+ 'event' : 'gtm4wp.formElementLeave',
23
+
24
+ 'inputID' : elem.getAttribute("id") || "(no input ID)",
25
+ 'inputName' : elem.getAttribute("name") || "(no input name)",
26
+ 'inputClass': elem.getAttribute("class") || "(no input class)",
27
+
28
+ 'formID' : elem.form.getAttribute("id") || "(no form ID)",
29
+ 'formName' : elem.form.getAttribute("name") || "(no form name)",
30
+ 'formClass': elem.form.getAttribute("class") || "(no form class)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  });
32
+ };
33
+ }, false);
js/gtm4wp-soundcloud.js CHANGED
@@ -1,137 +1,139 @@
1
- var gtm4wp_soundclound_percentage_tracking = 10;
2
- var gtm4wp_soundclound_percentage_tracking_marks = {};
3
-
4
- jQuery(function() {
5
- // jQuery( '[id^="soundcloudplayer_"]' ).each(function() {
6
- jQuery( 'iframe[src*="soundcloud.com"]' ).each(function() {
7
- var iframe = this,
8
- widget = SC.Widget( this ),
9
- jqframe = jQuery( iframe ),
10
- sound = {};
11
-
12
- widget.bind( SC.Widget.Events.READY, function() {
13
- widget.getCurrentSound(function( soundData ) {
14
-
15
- jqframe.attr( "data-player_id", soundData.id );
16
- jqframe.attr( "data-player_author", soundData.user.username );
17
- jqframe.attr( "data-player_title", soundData.title );
18
- jqframe.attr( "data-player_url", soundData.permalink_url );
19
- jqframe.attr( "data-player_duration", soundData.duration );
20
-
21
- sound = soundData;
22
-
23
- window[ gtm4wp_datalayer_name ].push({
24
- 'event': 'gtm4wp.mediaPlayerReady',
25
- 'mediaType': 'soundcloud',
26
- 'mediaData': {
27
- 'id': soundData.id,
28
- 'author': soundData.user.username,
29
- 'title': soundData.title,
30
- 'url': soundData.permalink_url,
31
- 'duration': soundData.duration
32
- },
33
- 'mediaCurrentTime': 0
34
- });
35
- }); // end of api call getDuration
36
-
37
- widget.bind( SC.Widget.Events.PLAY_PROGRESS, function( eventData ) {
38
- gtm4wp_onSoundCloudPercentageChange( eventData );
39
- });
40
-
41
- widget.bind( SC.Widget.Events.PLAY, function( eventData ) {
42
- gtm4wp_onSoundCloudPlayerStateChange( eventData, 'play' );
43
- });
44
-
45
- widget.bind( SC.Widget.Events.PAUSE, function( eventData ) {
46
- gtm4wp_onSoundCloudPlayerStateChange( eventData, 'pause' );
47
- });
48
-
49
- widget.bind( SC.Widget.Events.FINISH, function( eventData ) {
50
- gtm4wp_onSoundCloudPlayerStateChange( eventData, 'ended' );
51
- });
52
-
53
- widget.bind( SC.Widget.Events.SEEK, function( eventData ) {
54
- gtm4wp_onSoundCloudPlayerStateChange( eventData, 'seeked' );
55
- });
56
-
57
- widget.bind( SC.Widget.Events.CLICK_DOWNLOAD, function() {
58
- gtm4wp_onSoundCloudPlayerEvent( 'click-download' );
59
- });
60
-
61
- widget.bind( SC.Widget.Events.CLICK_BUY, function() {
62
- gtm4wp_onSoundCloudPlayerEvent( 'click-buy' );
63
- });
64
-
65
- widget.bind( SC.Widget.Events.OPEN_SHARE_PANEL, function() {
66
- gtm4wp_onSoundCloudPlayerEvent( 'open-share-panel' );
67
- });
68
-
69
- widget.bind( SC.Widget.Events.ERROR, function() {
70
- gtm4wp_onSoundCloudPlayerEvent( 'error' );
71
- });
72
- });
73
-
74
- var gtm4wp_onSoundCloudPlayerStateChange = function( eventData, playerState ) {
75
- window[ gtm4wp_datalayer_name ].push({
76
- 'event': 'gtm4wp.mediaPlayerStateChange',
77
- 'mediaType': 'soundcloud',
78
- 'mediaData': {
79
- 'id': sound.id,
80
- 'author': sound.user.username,
81
- 'title': sound.title,
82
- 'url': sound.permalink_url,
83
- 'duration': sound.duration
84
- },
85
- 'mediaCurrentTime': eventData.currentPosition,
86
- 'mediaPlayerState': playerState
87
- });
88
- };
89
-
90
- var gtm4wp_onSoundCloudPercentageChange = function( eventData ) {
91
- var mediaPercentage = Math.floor( eventData.currentPosition / sound.duration * 100 );
92
-
93
- if ( typeof gtm4wp_soundclound_percentage_tracking_marks[ sound.id ] == "undefined" ) {
94
- gtm4wp_soundclound_percentage_tracking_marks[ sound.id ] = [];
95
- }
96
-
97
- for( var i=0; i<100; i+=gtm4wp_soundclound_percentage_tracking ) {
98
- if ( ( mediaPercentage > i ) && ( gtm4wp_soundclound_percentage_tracking_marks[ sound.id ].indexOf( i ) == -1 ) ) {
99
- gtm4wp_soundclound_percentage_tracking_marks[ sound.id ].push( i );
100
-
101
- window[ gtm4wp_datalayer_name ].push({
102
- 'event': 'gtm4wp.mediaPlaybackPercentage',
103
- 'mediaType': 'soundcloud',
104
- 'mediaData': {
105
- 'id': sound.id,
106
- 'author': sound.user.username,
107
- 'title': sound.title,
108
- 'url': sound.permalink_url,
109
- 'duration': sound.duration
110
- },
111
- 'mediaCurrentTime': eventData.currentPosition,
112
- 'mediaPercentage': i
113
- });
114
- }
115
- }
116
- };
117
-
118
- var gtm4wp_onSoundCloudPlayerEvent = function( eventName ) {
119
- widget.getPosition(function( currentPosition ) {
120
- window[ gtm4wp_datalayer_name ].push({
121
- 'event': 'gtm4wp.mediaPlayerEvent',
122
- 'mediaType': 'soundcloud',
123
- 'mediaData': {
124
- 'id': sound.id,
125
- 'author': sound.user.username,
126
- 'title': sound.title,
127
- 'url': sound.permalink_url,
128
- 'duration': soundData.duration
129
- },
130
- 'mediaCurrentTime': currentPosition,
131
- 'mediaPlayerEvent': eventName
132
- });
133
- });
134
- };
135
-
136
- });
137
- });
 
 
1
+ let gtm4wp_soundclound_percentage_tracking = 10;
2
+ let gtm4wp_soundclound_percentage_tracking_marks = {};
3
+
4
+ window.addEventListener('DOMContentLoaded', function() {
5
+ const gtm4wp_soundcloud_frames = document.querySelectorAll( 'iframe[src*="soundcloud.com"]' );
6
+ if ( !gtm4wp_soundcloud_frames || gtm4wp_soundcloud_frames.length == 0 ) {
7
+ return;
8
+ }
9
+
10
+ gtm4wp_soundcloud_frames.forEach(function( soundcloud_frame ) {
11
+ let widget = SC.Widget( soundcloud_frame );
12
+ let sound = {};
13
+
14
+ widget.bind( SC.Widget.Events.READY, function() {
15
+ widget.getCurrentSound(function( soundData ) {
16
+
17
+ soundcloud_frame.setAttribute( "data-player_id", soundData.id );
18
+ soundcloud_frame.setAttribute( "data-player_author", soundData.user.username );
19
+ soundcloud_frame.setAttribute( "data-player_title", soundData.title );
20
+ soundcloud_frame.setAttribute( "data-player_url", soundData.permalink_url );
21
+ soundcloud_frame.setAttribute( "data-player_duration", soundData.duration );
22
+
23
+ sound = soundData;
24
+
25
+ window[ gtm4wp_datalayer_name ].push({
26
+ 'event': 'gtm4wp.mediaPlayerReady',
27
+ 'mediaType': 'soundcloud',
28
+ 'mediaData': {
29
+ 'id': soundData.id,
30
+ 'author': soundData.user.username,
31
+ 'title': soundData.title,
32
+ 'url': soundData.permalink_url,
33
+ 'duration': soundData.duration
34
+ },
35
+ 'mediaCurrentTime': 0
36
+ });
37
+ }); // end of api call getDuration
38
+
39
+ widget.bind( SC.Widget.Events.PLAY_PROGRESS, function( eventData ) {
40
+ gtm4wp_onSoundCloudPercentageChange( eventData );
41
+ });
42
+
43
+ widget.bind( SC.Widget.Events.PLAY, function( eventData ) {
44
+ gtm4wp_onSoundCloudPlayerStateChange( eventData, 'play' );
45
+ });
46
+
47
+ widget.bind( SC.Widget.Events.PAUSE, function( eventData ) {
48
+ gtm4wp_onSoundCloudPlayerStateChange( eventData, 'pause' );
49
+ });
50
+
51
+ widget.bind( SC.Widget.Events.FINISH, function( eventData ) {
52
+ gtm4wp_onSoundCloudPlayerStateChange( eventData, 'ended' );
53
+ });
54
+
55
+ widget.bind( SC.Widget.Events.SEEK, function( eventData ) {
56
+ gtm4wp_onSoundCloudPlayerStateChange( eventData, 'seeked' );
57
+ });
58
+
59
+ widget.bind( SC.Widget.Events.CLICK_DOWNLOAD, function() {
60
+ gtm4wp_onSoundCloudPlayerEvent( 'click-download' );
61
+ });
62
+
63
+ widget.bind( SC.Widget.Events.CLICK_BUY, function() {
64
+ gtm4wp_onSoundCloudPlayerEvent( 'click-buy' );
65
+ });
66
+
67
+ widget.bind( SC.Widget.Events.OPEN_SHARE_PANEL, function() {
68
+ gtm4wp_onSoundCloudPlayerEvent( 'open-share-panel' );
69
+ });
70
+
71
+ widget.bind( SC.Widget.Events.ERROR, function() {
72
+ gtm4wp_onSoundCloudPlayerEvent( 'error' );
73
+ });
74
+ });
75
+
76
+ const gtm4wp_onSoundCloudPlayerStateChange = function( eventData, playerState ) {
77
+ window[ gtm4wp_datalayer_name ].push({
78
+ 'event': 'gtm4wp.mediaPlayerStateChange',
79
+ 'mediaType': 'soundcloud',
80
+ 'mediaData': {
81
+ 'id': sound.id,
82
+ 'author': sound.user.username,
83
+ 'title': sound.title,
84
+ 'url': sound.permalink_url,
85
+ 'duration': sound.duration
86
+ },
87
+ 'mediaCurrentTime': eventData.currentPosition,
88
+ 'mediaPlayerState': playerState
89
+ });
90
+ };
91
+
92
+ const gtm4wp_onSoundCloudPercentageChange = function( eventData ) {
93
+ const mediaPercentage = Math.floor( eventData.currentPosition / sound.duration * 100 );
94
+
95
+ if ( typeof gtm4wp_soundclound_percentage_tracking_marks[ sound.id ] == "undefined" ) {
96
+ gtm4wp_soundclound_percentage_tracking_marks[ sound.id ] = [];
97
+ }
98
+
99
+ for( let i=0; i<100; i+=gtm4wp_soundclound_percentage_tracking ) {
100
+ if ( ( mediaPercentage > i ) && ( gtm4wp_soundclound_percentage_tracking_marks[ sound.id ].indexOf( i ) == -1 ) ) {
101
+ gtm4wp_soundclound_percentage_tracking_marks[ sound.id ].push( i );
102
+
103
+ window[ gtm4wp_datalayer_name ].push({
104
+ 'event': 'gtm4wp.mediaPlaybackPercentage',
105
+ 'mediaType': 'soundcloud',
106
+ 'mediaData': {
107
+ 'id': sound.id,
108
+ 'author': sound.user.username,
109
+ 'title': sound.title,
110
+ 'url': sound.permalink_url,
111
+ 'duration': sound.duration
112
+ },
113
+ 'mediaCurrentTime': eventData.currentPosition,
114
+ 'mediaPercentage': i
115
+ });
116
+ }
117
+ }
118
+ };
119
+
120
+ const gtm4wp_onSoundCloudPlayerEvent = function( eventName ) {
121
+ widget.getPosition(function( currentPosition ) {
122
+ window[ gtm4wp_datalayer_name ].push({
123
+ 'event': 'gtm4wp.mediaPlayerEvent',
124
+ 'mediaType': 'soundcloud',
125
+ 'mediaData': {
126
+ 'id': sound.id,
127
+ 'author': sound.user.username,
128
+ 'title': sound.title,
129
+ 'url': sound.permalink_url,
130
+ 'duration': soundData.duration
131
+ },
132
+ 'mediaCurrentTime': currentPosition,
133
+ 'mediaPlayerEvent': eventName
134
+ });
135
+ });
136
+ };
137
+
138
+ });
139
+ });
js/gtm4wp-users.js DELETED
@@ -1,39 +0,0 @@
1
- function gtm4wp_set_cookie( cookiename, cookievalue, expiredays ) {
2
- var d = new Date();
3
- d.setTime(d.getTime() + (expiredays*24*60*60*1000));
4
- var expires = "expires="+ d.toUTCString();
5
-
6
- document.cookie = cookiename + "=" + cookievalue + ";" + expires + ";path=/";
7
- }
8
-
9
- function gtm4wp_get_cookie( cookiename ) {
10
- var decoded_cookie_list = decodeURIComponent(document.cookie).split(';');
11
- var onecookie = '';
12
-
13
- for( var i=0; i<decoded_cookie_list.length; i++ ) {
14
- onecookie = decoded_cookie_list[i].trim();
15
- if ( 0 == onecookie.indexOf( cookiename ) ) {
16
- return onecookie.substring( cookiename.length+1, onecookie.length );
17
- }
18
- }
19
-
20
- return "";
21
- }
22
-
23
- var gtm4wp_user_logged_in = gtm4wp_get_cookie( 'gtm4wp_user_logged_in' );
24
- if ( gtm4wp_user_logged_in === "1" ) {
25
- window[ gtm4wp_datalayer_name ].push({
26
- 'event': 'gtm4wp.userLoggedIn',
27
- });
28
-
29
- gtm4wp_set_cookie( 'gtm4wp_user_logged_in', '', -1 );
30
- }
31
-
32
- var gtm4wp_new_user_registered = gtm4wp_get_cookie( 'gtm4wp_user_registered' );
33
- if ( gtm4wp_new_user_registered === "1" ) {
34
- window[ gtm4wp_datalayer_name ].push({
35
- 'event': 'gtm4wp.userRegistered',
36
- });
37
-
38
- gtm4wp_set_cookie( 'gtm4wp_user_registered', '', -1 );
39
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
js/gtm4wp-vimeo.js CHANGED
@@ -1,268 +1,273 @@
1
- var gtm4wp_vimeo_percentage_tracking = 10;
2
- var gtm4wp_vimeo_percentage_tracking_marks = {};
3
-
4
- jQuery(function() {
5
- jQuery( 'iframe[src*="vimeo.com"]' ).each(function() {
6
- var vimeoapi = new Vimeo.Player( this ),
7
- jqframe = jQuery( this ),
8
- videourl = jqframe
9
- .attr( "src" )
10
- .split( "?" )
11
- .shift(),
12
- videoid = videourl.split( "/" ).pop();
13
-
14
- jqframe.attr( "data-player_id", videoid );
15
- jqframe.attr( "data-player_url", videourl );
16
-
17
- vimeoapi.getVideoTitle().then( function( title ) {
18
- jqframe.attr( "data-player_title", title );
19
-
20
- vimeoapi.getDuration().then( function( duration ) {
21
-
22
- jqframe.attr( "data-player_duration", duration );
23
-
24
- window[ gtm4wp_datalayer_name ].push({
25
- 'event': 'gtm4wp.mediaPlayerReady',
26
- 'mediaType': 'vimeo',
27
- 'mediaData': {
28
- 'id': videoid,
29
- 'author': '',
30
- 'title': jqframe.attr( "data-player_title" ),
31
- 'url': videourl,
32
- 'duration': duration
33
- },
34
- 'mediaCurrentTime': 0
35
- });
36
-
37
- }).catch( function( error ) {
38
-
39
- window[ gtm4wp_datalayer_name ].push({
40
- 'event': 'gtm4wp.mediaPlayerEvent',
41
- 'mediaType': 'vimeo',
42
- 'mediaData': {
43
- 'id': videoid,
44
- 'author': '',
45
- 'title': jqframe.attr( "data-player_title" ),
46
- 'url': videourl,
47
- 'duration': 0
48
- },
49
- 'mediaCurrentTime': 0,
50
- 'mediaPlayerEvent': 'error',
51
- 'mediaPlayerEventParam': error
52
- });
53
-
54
- }); // end of api call getDuration
55
-
56
- }).catch( function( error ) {
57
-
58
- window[ gtm4wp_datalayer_name ].push({
59
- 'event': 'gtm4wp.mediaPlayerEvent',
60
- 'mediaType': 'vimeo',
61
- 'mediaData': {
62
- 'id': videoid,
63
- 'author': '',
64
- 'title': "Unknown title",
65
- 'url': videourl,
66
- 'duration': 0
67
- },
68
- 'mediaCurrentTime': 0,
69
- 'mediaPlayerEvent': 'error',
70
- 'mediaPlayerEventParam': error
71
- });
72
-
73
- }); // end of api call getVideoTitle
74
-
75
- vimeoapi.on( 'play', function( data ) {
76
- gtm4wp_onVimeoPlayerStateChange( 'play', data );
77
- });
78
-
79
- vimeoapi.on( 'pause', function( data ) {
80
- gtm4wp_onVimeoPlayerStateChange( 'pause', data );
81
- });
82
-
83
- vimeoapi.on( 'ended', function( data ) {
84
- gtm4wp_onVimeoPlayerStateChange( 'ended', data );
85
- });
86
-
87
- vimeoapi.on( 'seeked', function( data ) {
88
- gtm4wp_onVimeoPlayerStateChange( 'seeked', data );
89
- });
90
-
91
- vimeoapi.on( 'texttrackchange', function( data ) {
92
-
93
- vimeoapi.getCurrentTime().then( function( seconds ) {
94
-
95
- window[ gtm4wp_datalayer_name ].push({
96
- 'event': 'gtm4wp.mediaPlayerEvent',
97
- 'mediaType': 'vimeo',
98
- 'mediaData': {
99
- 'id': videoid,
100
- 'author': '',
101
- 'title': jqframe.attr( "data-player_title" ),
102
- 'url': jqframe.attr( "data-player_url" ),
103
- 'duration': jqframe.attr( "data-player_duration" )
104
- },
105
- 'mediaPlayerEvent': 'texttrackchange',
106
- 'mediaPlayerEventParam': data,
107
- 'mediaCurrentTime': seconds
108
- });
109
-
110
- }).catch( function( error ) {
111
-
112
- window[ gtm4wp_datalayer_name ].push({
113
- 'event': 'gtm4wp.mediaPlayerEvent',
114
- 'mediaType': 'vimeo',
115
- 'mediaData': {
116
- 'id': videoid,
117
- 'author': '',
118
- 'title': "Unknown title",
119
- 'url': videourl,
120
- 'duration': jqframe.attr( "data-player_duration" )
121
- },
122
- 'mediaCurrentTime': 0,
123
- 'mediaPlayerEvent': 'error',
124
- 'mediaPlayerEventParam': error
125
- });
126
-
127
- }); // end call api getCurrentTime()
128
-
129
- });
130
-
131
- vimeoapi.on( 'volumechange', function( data ) {
132
-
133
- vimeoapi.getCurrentTime().then( function( seconds ) {
134
-
135
- window[ gtm4wp_datalayer_name ].push({
136
- 'event': 'gtm4wp.mediaPlayerEvent',
137
- 'mediaType': 'vimeo',
138
- 'mediaData': {
139
- 'id': videoid,
140
- 'author': '',
141
- 'title': jqframe.attr( "data-player_title" ),
142
- 'url': jqframe.attr( "data-player_url" ),
143
- 'duration': jqframe.attr( "data-player_duration" )
144
- },
145
- 'mediaPlayerEvent': 'volumechange',
146
- 'mediaPlayerEventParam': data.volume,
147
- 'mediaCurrentTime': seconds
148
-
149
- });
150
-
151
- }).catch( function( error ) {
152
-
153
- window[ gtm4wp_datalayer_name ].push({
154
- 'event': 'gtm4wp.mediaPlayerEvent',
155
- 'mediaType': 'vimeo',
156
- 'mediaData': {
157
- 'id': videoid,
158
- 'author': '',
159
- 'title': "Unknown title",
160
- 'url': videourl,
161
- 'duration': jqframe.attr( "data-player_duration" )
162
- },
163
- 'mediaCurrentTime': 0,
164
- 'mediaPlayerEvent': 'error',
165
- 'mediaPlayerEventParam': error
166
- });
167
-
168
- }); // end call api getCurrentTime()
169
-
170
- });
171
-
172
- vimeoapi.on( 'error', function( data ) {
173
-
174
- vimeoapi.getCurrentTime().then( function( seconds ) {
175
-
176
- window[ gtm4wp_datalayer_name ].push({
177
- 'event': 'gtm4wp.mediaPlayerEvent',
178
- 'mediaType': 'vimeo',
179
- 'mediaData': {
180
- 'id': videoid,
181
- 'author': '',
182
- 'title': jqframe.attr( "data-player_title" ),
183
- 'url': jqframe.attr( "data-player_url" ),
184
- 'duration': jqframe.attr( "data-player_duration" )
185
- },
186
- 'mediaPlayerEvent': 'error',
187
- 'mediaPlayerEventParam': data,
188
- 'mediaCurrentTime': seconds
189
-
190
- });
191
-
192
- }).catch( function( error ) {
193
-
194
- window[ gtm4wp_datalayer_name ].push({
195
- 'event': 'gtm4wp.mediaPlayerEvent',
196
- 'mediaType': 'vimeo',
197
- 'mediaData': {
198
- 'id': videoid,
199
- 'author': '',
200
- 'title': "Unknown title",
201
- 'url': videourl,
202
- 'duration': jqframe.attr( "data-player_duration" )
203
- },
204
- 'mediaCurrentTime': 0,
205
- 'mediaPlayerEvent': 'error',
206
- 'mediaPlayerEventParam': error
207
- });
208
-
209
- }); // end call api getCurrentTime()
210
-
211
- });
212
-
213
- vimeoapi.on( 'timeupdate', function( data ) {
214
- gtm4wp_onVimeoPercentageChange( data );
215
- });
216
-
217
- var gtm4wp_onVimeoPlayerStateChange = function( player_state, data ) {
218
-
219
- window[ gtm4wp_datalayer_name ].push({
220
- 'event': 'gtm4wp.mediaPlayerStateChange',
221
- 'mediaType': 'vimeo',
222
- 'mediaData': {
223
- 'id': videoid,
224
- 'author': '',
225
- 'title': jqframe.attr( "data-player_title" ),
226
- 'url': jqframe.attr( "data-player_url" ),
227
- 'duration': data.duration
228
- },
229
- 'mediaPlayerState': player_state,
230
- 'mediaCurrentTime': data.seconds
231
- });
232
-
233
- };
234
-
235
- var gtm4wp_onVimeoPercentageChange = function( data ) {
236
-
237
- var videoDuration = data.duration;
238
- var videoPercentage = Math.floor( data.seconds / videoDuration * 100 );
239
-
240
- if ( typeof gtm4wp_vimeo_percentage_tracking_marks[ videoid ] == "undefined" ) {
241
- gtm4wp_vimeo_percentage_tracking_marks[ videoid ] = [];
242
- }
243
-
244
- for( var i=0; i<100; i+=gtm4wp_vimeo_percentage_tracking ) {
245
- if ( ( videoPercentage > i ) && ( gtm4wp_vimeo_percentage_tracking_marks[ videoid ].indexOf( i ) == -1 ) ) {
246
-
247
- gtm4wp_vimeo_percentage_tracking_marks[ videoid ].push( i );
248
-
249
- window[ gtm4wp_datalayer_name ].push({
250
- 'event': 'gtm4wp.mediaPlaybackPercentage',
251
- 'mediaType': 'vimeo',
252
- 'mediaData': {
253
- 'id': videoid,
254
- 'author': '',
255
- 'title': jqframe.attr( "data-player_title" ),
256
- 'url': jqframe.attr( "data-player_url" ),
257
- 'duration': videoDuration
258
- },
259
- 'mediaCurrentTime': data.seconds,
260
- 'mediaPercentage': i
261
- });
262
-
263
- }
264
- }
265
- };
266
-
267
- });
268
- });
 
 
 
 
 
1
+ let gtm4wp_vimeo_percentage_tracking = 10;
2
+ let gtm4wp_vimeo_percentage_tracking_marks = {};
3
+
4
+ window.addEventListener('DOMContentLoaded', function() {
5
+ const gtm4wp_vimeo_frames = document.querySelectorAll( 'iframe[src*="vimeo.com"]' );
6
+ if ( !gtm4wp_vimeo_frames || gtm4wp_vimeo_frames.length == 0 ) {
7
+ return;
8
+ }
9
+
10
+ gtm4wp_vimeo_frames.forEach(function( vimeo_frame ) {
11
+ const vimeoapi = new Vimeo.Player( vimeo_frame );
12
+ let videourl = vimeo_frame
13
+ .getAttribute( "src" )
14
+ .split( "?" )
15
+ .shift();
16
+ let videoid = videourl.split( "/" )
17
+ .pop();
18
+
19
+ vimeo_frame.setAttribute( "data-player_id", videoid );
20
+ vimeo_frame.setAttribute( "data-player_url", videourl );
21
+
22
+ vimeoapi.getVideoTitle().then( function( title ) {
23
+ vimeo_frame.setAttribute( "data-player_title", title );
24
+
25
+ vimeoapi.getDuration().then( function( duration ) {
26
+
27
+ vimeo_frame.setAttribute( "data-player_duration", duration );
28
+
29
+ window[ gtm4wp_datalayer_name ].push({
30
+ 'event': 'gtm4wp.mediaPlayerReady',
31
+ 'mediaType': 'vimeo',
32
+ 'mediaData': {
33
+ 'id': videoid,
34
+ 'author': '',
35
+ 'title': vimeo_frame.getAttribute( "data-player_title" ),
36
+ 'url': videourl,
37
+ 'duration': duration
38
+ },
39
+ 'mediaCurrentTime': 0
40
+ });
41
+
42
+ }).catch( function( error ) {
43
+
44
+ window[ gtm4wp_datalayer_name ].push({
45
+ 'event': 'gtm4wp.mediaPlayerEvent',
46
+ 'mediaType': 'vimeo',
47
+ 'mediaData': {
48
+ 'id': videoid,
49
+ 'author': '',
50
+ 'title': vimeo_frame.getAttribute( "data-player_title" ),
51
+ 'url': videourl,
52
+ 'duration': 0
53
+ },
54
+ 'mediaCurrentTime': 0,
55
+ 'mediaPlayerEvent': 'error',
56
+ 'mediaPlayerEventParam': error
57
+ });
58
+
59
+ }); // end of api call getDuration
60
+
61
+ }).catch( function( error ) {
62
+
63
+ window[ gtm4wp_datalayer_name ].push({
64
+ 'event': 'gtm4wp.mediaPlayerEvent',
65
+ 'mediaType': 'vimeo',
66
+ 'mediaData': {
67
+ 'id': videoid,
68
+ 'author': '',
69
+ 'title': "Unknown title",
70
+ 'url': videourl,
71
+ 'duration': 0
72
+ },
73
+ 'mediaCurrentTime': 0,
74
+ 'mediaPlayerEvent': 'error',
75
+ 'mediaPlayerEventParam': error
76
+ });
77
+
78
+ }); // end of api call getVideoTitle
79
+
80
+ vimeoapi.on( 'play', function( data ) {
81
+ gtm4wp_onVimeoPlayerStateChange( 'play', data );
82
+ });
83
+
84
+ vimeoapi.on( 'pause', function( data ) {
85
+ gtm4wp_onVimeoPlayerStateChange( 'pause', data );
86
+ });
87
+
88
+ vimeoapi.on( 'ended', function( data ) {
89
+ gtm4wp_onVimeoPlayerStateChange( 'ended', data );
90
+ });
91
+
92
+ vimeoapi.on( 'seeked', function( data ) {
93
+ gtm4wp_onVimeoPlayerStateChange( 'seeked', data );
94
+ });
95
+
96
+ vimeoapi.on( 'texttrackchange', function( data ) {
97
+
98
+ vimeoapi.getCurrentTime().then( function( seconds ) {
99
+
100
+ window[ gtm4wp_datalayer_name ].push({
101
+ 'event': 'gtm4wp.mediaPlayerEvent',
102
+ 'mediaType': 'vimeo',
103
+ 'mediaData': {
104
+ 'id': videoid,
105
+ 'author': '',
106
+ 'title': vimeo_frame.getAttribute( "data-player_title" ),
107
+ 'url': vimeo_frame.getAttribute( "data-player_url" ),
108
+ 'duration': vimeo_frame.getAttribute( "data-player_duration" )
109
+ },
110
+ 'mediaPlayerEvent': 'texttrackchange',
111
+ 'mediaPlayerEventParam': data,
112
+ 'mediaCurrentTime': seconds
113
+ });
114
+
115
+ }).catch( function( error ) {
116
+
117
+ window[ gtm4wp_datalayer_name ].push({
118
+ 'event': 'gtm4wp.mediaPlayerEvent',
119
+ 'mediaType': 'vimeo',
120
+ 'mediaData': {
121
+ 'id': videoid,
122
+ 'author': '',
123
+ 'title': "Unknown title",
124
+ 'url': videourl,
125
+ 'duration': vimeo_frame.getAttribute( "data-player_duration" )
126
+ },
127
+ 'mediaCurrentTime': 0,
128
+ 'mediaPlayerEvent': 'error',
129
+ 'mediaPlayerEventParam': error
130
+ });
131
+
132
+ }); // end call api getCurrentTime()
133
+
134
+ });
135
+
136
+ vimeoapi.on( 'volumechange', function( data ) {
137
+
138
+ vimeoapi.getCurrentTime().then( function( seconds ) {
139
+
140
+ window[ gtm4wp_datalayer_name ].push({
141
+ 'event': 'gtm4wp.mediaPlayerEvent',
142
+ 'mediaType': 'vimeo',
143
+ 'mediaData': {
144
+ 'id': videoid,
145
+ 'author': '',
146
+ 'title': vimeo_frame.getAttribute( "data-player_title" ),
147
+ 'url': vimeo_frame.getAttribute( "data-player_url" ),
148
+ 'duration': vimeo_frame.getAttribute( "data-player_duration" )
149
+ },
150
+ 'mediaPlayerEvent': 'volumechange',
151
+ 'mediaPlayerEventParam': data.volume,
152
+ 'mediaCurrentTime': seconds
153
+
154
+ });
155
+
156
+ }).catch( function( error ) {
157
+
158
+ window[ gtm4wp_datalayer_name ].push({
159
+ 'event': 'gtm4wp.mediaPlayerEvent',
160
+ 'mediaType': 'vimeo',
161
+ 'mediaData': {
162
+ 'id': videoid,
163
+ 'author': '',
164
+ 'title': "Unknown title",
165
+ 'url': videourl,
166
+ 'duration': vimeo_frame.getAttribute( "data-player_duration" )
167
+ },
168
+ 'mediaCurrentTime': 0,
169
+ 'mediaPlayerEvent': 'error',
170
+ 'mediaPlayerEventParam': error
171
+ });
172
+
173
+ }); // end call api getCurrentTime()
174
+
175
+ });
176
+
177
+ vimeoapi.on( 'error', function( data ) {
178
+
179
+ vimeoapi.getCurrentTime().then( function( seconds ) {
180
+
181
+ window[ gtm4wp_datalayer_name ].push({
182
+ 'event': 'gtm4wp.mediaPlayerEvent',
183
+ 'mediaType': 'vimeo',
184
+ 'mediaData': {
185
+ 'id': videoid,
186
+ 'author': '',
187
+ 'title': vimeo_frame.getAttribute( "data-player_title" ),
188
+ 'url': vimeo_frame.getAttribute( "data-player_url" ),
189
+ 'duration': vimeo_frame.getAttribute( "data-player_duration" )
190
+ },
191
+ 'mediaPlayerEvent': 'error',
192
+ 'mediaPlayerEventParam': data,
193
+ 'mediaCurrentTime': seconds
194
+
195
+ });
196
+
197
+ }).catch( function( error ) {
198
+
199
+ window[ gtm4wp_datalayer_name ].push({
200
+ 'event': 'gtm4wp.mediaPlayerEvent',
201
+ 'mediaType': 'vimeo',
202
+ 'mediaData': {
203
+ 'id': videoid,
204
+ 'author': '',
205
+ 'title': "Unknown title",
206
+ 'url': videourl,
207
+ 'duration': vimeo_frame.getAttribute( "data-player_duration" )
208
+ },
209
+ 'mediaCurrentTime': 0,
210
+ 'mediaPlayerEvent': 'error',
211
+ 'mediaPlayerEventParam': error
212
+ });
213
+
214
+ }); // end call api getCurrentTime()
215
+
216
+ });
217
+
218
+ vimeoapi.on( 'timeupdate', function( data ) {
219
+ gtm4wp_onVimeoPercentageChange( data );
220
+ });
221
+
222
+ const gtm4wp_onVimeoPlayerStateChange = function( player_state, data ) {
223
+
224
+ window[ gtm4wp_datalayer_name ].push({
225
+ 'event': 'gtm4wp.mediaPlayerStateChange',
226
+ 'mediaType': 'vimeo',
227
+ 'mediaData': {
228
+ 'id': videoid,
229
+ 'author': '',
230
+ 'title': vimeo_frame.getAttribute( "data-player_title" ),
231
+ 'url': vimeo_frame.getAttribute( "data-player_url" ),
232
+ 'duration': data.duration
233
+ },
234
+ 'mediaPlayerState': player_state,
235
+ 'mediaCurrentTime': data.seconds
236
+ });
237
+
238
+ };
239
+
240
+ const gtm4wp_onVimeoPercentageChange = function( data ) {
241
+
242
+ let videoDuration = data.duration;
243
+ let videoPercentage = Math.floor( data.seconds / videoDuration * 100 );
244
+
245
+ if ( typeof gtm4wp_vimeo_percentage_tracking_marks[ videoid ] == "undefined" ) {
246
+ gtm4wp_vimeo_percentage_tracking_marks[ videoid ] = [];
247
+ }
248
+
249
+ for( let i=0; i<100; i+=gtm4wp_vimeo_percentage_tracking ) {
250
+ if ( ( videoPercentage > i ) && ( gtm4wp_vimeo_percentage_tracking_marks[ videoid ].indexOf( i ) == -1 ) ) {
251
+
252
+ gtm4wp_vimeo_percentage_tracking_marks[ videoid ].push( i );
253
+
254
+ window[ gtm4wp_datalayer_name ].push({
255
+ 'event': 'gtm4wp.mediaPlaybackPercentage',
256
+ 'mediaType': 'vimeo',
257
+ 'mediaData': {
258
+ 'id': videoid,
259
+ 'author': '',
260
+ 'title': vimeo_frame.getAttribute( "data-player_title" ),
261
+ 'url': vimeo_frame.getAttribute( "data-player_url" ),
262
+ 'duration': videoDuration
263
+ },
264
+ 'mediaCurrentTime': data.seconds,
265
+ 'mediaPercentage': i
266
+ });
267
+
268
+ }
269
+ }
270
+ };
271
+
272
+ });
273
+ });
js/gtm4wp-woocommerce-classic.js CHANGED
@@ -1,29 +1,32 @@
1
- jQuery(function() {
2
- jQuery( document ).on( 'click', '.add_to_cart_button:not(.product_type_variable, .product_type_grouped, .single_add_to_cart_button)', function() {
3
- var productdata = jQuery( this ).closest( '.product' ).find( '.gtm4wp_productdata' );
4
-
5
- window[ gtm4wp_datalayer_name ].push({
6
- 'event': 'gtm4wp.addProductToCart',
7
- 'productName': productdata.data( 'gtm4wp_product_name' ),
8
- 'productSKU': jQuery( this ).data( 'product_sku' ),
9
- 'productID': jQuery( this ).data( 'product_id' ),
10
- });
11
- });
12
-
13
- jQuery( document ).on( 'click', '.single_add_to_cart_button', function() {
14
- var _product_form = jQuery( this ).closest( 'form.cart' );
15
- var _product_id = jQuery( '[name=gtm4wp_id]', _product_form ).val();
16
- var _product_name = jQuery( '[name=gtm4wp_name]', _product_form ).val();
17
- var _product_sku = jQuery( '[name=gtm4wp_sku]', _product_form ).val();
18
- var _product_is_grouped = jQuery( _product_form ).hasClass( 'grouped_form' );
19
-
20
- if ( ! _product_is_grouped ) {
21
- window[ gtm4wp_datalayer_name ].push({
22
- 'event': 'gtm4wp.addProductToCart',
23
- 'productName': _product_name,
24
- 'productSKU': _product_sku,
25
- 'productID': _product_id
26
- });
27
- }
28
- });
29
- });
 
 
 
1
+ // this part of the code is deprecated and will be removed in a later version
2
+ // therefore jQuery usage will be not rewritten
3
+ // turn of the deprecated standard/classic ecommerce feature and this code will not execute
4
+ jQuery(function() {
5
+ jQuery( document ).on( 'click', '.add_to_cart_button:not(.product_type_variable, .product_type_grouped, .single_add_to_cart_button)', function() {
6
+ var productdata = jQuery( this ).closest( '.product' ).find( '.gtm4wp_productdata' );
7
+
8
+ window[ gtm4wp_datalayer_name ].push({
9
+ 'event': 'gtm4wp.addProductToCart',
10
+ 'productName': productdata.data( 'gtm4wp_product_name' ),
11
+ 'productSKU': jQuery( this ).data( 'product_sku' ),
12
+ 'productID': jQuery( this ).data( 'product_id' ),
13
+ });
14
+ });
15
+
16
+ jQuery( document ).on( 'click', '.single_add_to_cart_button', function() {
17
+ var _product_form = jQuery( this ).closest( 'form.cart' );
18
+ var _product_id = jQuery( '[name=gtm4wp_id]', _product_form ).val();
19
+ var _product_name = jQuery( '[name=gtm4wp_name]', _product_form ).val();
20
+ var _product_sku = jQuery( '[name=gtm4wp_sku]', _product_form ).val();
21
+ var _product_is_grouped = jQuery( _product_form ).hasClass( 'grouped_form' );
22
+
23
+ if ( ! _product_is_grouped ) {
24
+ window[ gtm4wp_datalayer_name ].push({
25
+ 'event': 'gtm4wp.addProductToCart',
26
+ 'productName': _product_name,
27
+ 'productSKU': _product_sku,
28
+ 'productID': _product_id
29
+ });
30
+ }
31
+ });
32
+ });
js/gtm4wp-woocommerce-enhanced.js CHANGED
@@ -1,16 +1,23 @@
1
- var gtm4wp_last_selected_product_variation;
2
- var gtm4wp_changedetail_fired_during_pageload=false;
 
 
 
 
 
 
 
3
 
4
  function gtm4wp_map_eec_to_ga4( productdata ) {
5
- if (!productdata) {
6
  return;
7
  }
8
 
9
- var category_path = productdata.category ? productdata.category : '';
10
- var category_parts = category_path.toString().split('/');
11
 
12
  // default, required parameters
13
- var ga4_product = {
14
  'item_id': productdata.id ? productdata.id : '',
15
  'item_name': productdata.name ? productdata.name : '',
16
  'item_brand': productdata.brand ? productdata.brand : '',
@@ -22,7 +29,7 @@ function gtm4wp_map_eec_to_ga4( productdata ) {
22
  ga4_product.item_category = category_parts[0];
23
  } else if ( category_parts.length > 1 ) {
24
  ga4_product.item_category = category_parts[0];
25
- for( var i=1; i < Math.min( 5, category_parts.length ); i++ ) {
26
  ga4_product[ 'item_category_' + (i+1) ] = category_parts[i];
27
  }
28
  }
@@ -51,17 +58,22 @@ function gtm4wp_map_eec_to_ga4( productdata ) {
51
  }
52
 
53
  function gtm4wp_handle_cart_qty_change() {
54
- jQuery( '.product-quantity input.qty' ).each(function() {
55
- var _original_value = jQuery( this ).prop( 'defaultValue' );
56
 
57
- var _current_value = parseInt( jQuery( this ).val() );
58
- if ( Number.isNaN( _current_value ) ) {
59
- _current_value = _original_value;
60
  }
61
 
62
- if ( _original_value != _current_value ) {
63
- var productdata = jQuery( this ).closest( '.cart_item' ).find( '.remove' );
64
- var productprice = productdata.data( 'gtm4wp_product_price' );
 
 
 
 
 
65
 
66
  if ( typeof productprice == "string" ) {
67
  productprice = parseFloat( productprice );
@@ -72,16 +84,18 @@ function gtm4wp_handle_cart_qty_change() {
72
  productprice = 0;
73
  }
74
 
75
- if ( _original_value < _current_value ) {
76
- var product_data = {
77
- 'name': productdata.data( 'gtm4wp_product_name' ),
78
- 'id': productdata.data( 'gtm4wp_product_id' ),
 
 
79
  'price': productprice.toFixed(2),
80
- 'category': productdata.data( 'gtm4wp_product_cat' ),
81
- 'variant': productdata.data( 'gtm4wp_product_variant' ),
82
- 'stocklevel': productdata.data( 'gtm4wp_product_stocklevel' ),
83
- 'brand': productdata.data( 'gtm4wp_product_brand' ),
84
- 'quantity': _current_value - _original_value
85
  };
86
 
87
  // fire ga3 version
@@ -100,20 +114,21 @@ function gtm4wp_handle_cart_qty_change() {
100
  'event': 'add_to_cart',
101
  'ecommerce': {
102
  'currency': gtm4wp_currency, // ga4 version
103
- 'value': productprice.toFixed(2) * (_current_value - _original_value),
104
  'items': [ gtm4wp_map_eec_to_ga4( product_data ) ]
105
  }
106
  });
107
  } else {
108
- var product_data = {
109
- 'name': productdata.data( 'gtm4wp_product_name' ),
110
- 'id': productdata.data( 'gtm4wp_product_id' ),
 
111
  'price': productprice.toFixed(2),
112
- 'category': productdata.data( 'gtm4wp_product_cat' ),
113
- 'variant': productdata.data( 'gtm4wp_product_variant' ),
114
- 'stocklevel': productdata.data( 'gtm4wp_product_stocklevel' ),
115
- 'brand': productdata.data( 'gtm4wp_product_brand' ),
116
- 'quantity': _original_value - _current_value
117
  };
118
 
119
  // fire ga3 version
@@ -132,7 +147,7 @@ function gtm4wp_handle_cart_qty_change() {
132
  'event': 'remove_from_cart',
133
  'ecommerce': {
134
  'currency': gtm4wp_currency,
135
- 'value': productprice.toFixed(2) * (_original_value - _current_value),
136
  'items': [ gtm4wp_map_eec_to_ga4( product_data ) ]
137
  }
138
  });
@@ -141,20 +156,173 @@ function gtm4wp_handle_cart_qty_change() {
141
  }); // end each qty field
142
  } // end gtm4wp_handle_cart_qty_change()
143
 
144
- jQuery(function() {
145
- var is_cart = jQuery( 'body' ).hasClass( 'woocommerce-cart' );
146
- var is_checkout = jQuery( 'body' ).hasClass( 'woocommerce-checkout' );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
  // track impressions of products in product lists
149
- if ( jQuery( '.gtm4wp_productdata,.widget-product-item' ).length > 0 ) {
150
- var products = [];
151
- var ga4_products = [];
152
- var productdata, productprice=0;
153
- var product_data;
154
 
155
- jQuery( '.gtm4wp_productdata,.widget-product-item' ).each( function() {
156
- productdata = jQuery( this );
157
- productprice = productdata.data( 'gtm4wp_product_price' );
158
 
159
  if ( typeof productprice == "string" ) {
160
  productprice = parseFloat( productprice );
@@ -166,22 +334,25 @@ jQuery(function() {
166
  }
167
 
168
  product_data = {
169
- 'name': productdata.data( 'gtm4wp_product_name' ),
170
- 'id': productdata.data( 'gtm4wp_product_id' ),
171
  'price': productprice.toFixed(2),
172
- 'category': productdata.data( 'gtm4wp_product_cat' ),
173
- 'position': productdata.data( 'gtm4wp_product_listposition' ),
174
- 'list': productdata.data( 'gtm4wp_productlist_name' ),
175
- 'stocklevel': productdata.data( 'gtm4wp_product_stocklevel' ),
176
- 'brand': productdata.data( 'gtm4wp_product_brand' )
177
  };
 
178
  products.push(product_data);
179
  ga4_products.push( gtm4wp_map_eec_to_ga4( product_data ) );
180
  });
181
 
182
  if ( gtm4wp_product_per_impression > 0 ) {
183
  // Need to split the product submissions up into chunks in order to avoid the GA 8kb submission limit
184
- var chunk, ga4_chunk;
 
 
185
  while ( products.length ) {
186
  chunk = products.splice( 0, gtm4wp_product_per_impression );
187
  ga4_chunk = ga4_products.splice( 0, gtm4wp_product_per_impression );
@@ -230,9 +401,30 @@ jQuery(function() {
230
  }
231
 
232
  // track add to cart events for simple products in product lists
233
- jQuery( document ).on( 'click', '.add_to_cart_button:not(.product_type_variable, .product_type_grouped, .single_add_to_cart_button)', function() {
234
- var productdata = jQuery( this ).closest( '.product' ).find( '.gtm4wp_productdata' );
235
- var productprice = productdata.data( 'gtm4wp_product_price' );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
 
237
  if ( typeof productprice == "string" ) {
238
  productprice = parseFloat( productprice );
@@ -243,13 +435,13 @@ jQuery(function() {
243
  productprice = 0;
244
  }
245
 
246
- var product_data = {
247
- 'name': productdata.data( 'gtm4wp_product_name' ),
248
- 'id': productdata.data( 'gtm4wp_product_id' ),
249
  'price': productprice.toFixed(2),
250
- 'category': productdata.data( 'gtm4wp_product_cat' ),
251
- 'stocklevel': productdata.data( 'gtm4wp_product_stocklevel' ),
252
- 'brand': productdata.data( 'gtm4wp_product_brand' ),
253
  'quantity': 1
254
  };
255
 
@@ -276,14 +468,35 @@ jQuery(function() {
276
  });
277
 
278
  // track add to cart events for products on product detail pages
279
- jQuery( document ).on( 'click', '.single_add_to_cart_button:not(.disabled)', function() {
280
- var product_form = jQuery( this ).closest( 'form.cart' );
281
- var product_variant_id = jQuery( '[name=variation_id]', product_form );
282
- var product_is_grouped = jQuery( product_form ).hasClass( 'grouped_form' );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
283
 
284
  if ( product_variant_id.length > 0 ) {
285
  if ( gtm4wp_last_selected_product_variation ) {
286
- gtm4wp_last_selected_product_variation.quantity = jQuery( '[name=quantity]', product_form ).val();
287
 
288
  // fire ga3 version
289
  window[ gtm4wp_datalayer_name ].push({
@@ -307,33 +520,31 @@ jQuery(function() {
307
  });
308
  }
309
  } else if ( product_is_grouped ) {
310
- var products_in_group = jQuery( '.grouped_form .gtm4wp_productdata' );
311
- var products = [];
312
- var ga4_products = [];
313
- var sum_value = 0;
314
 
315
- products_in_group.each( function() {
316
- var productdata = jQuery( this );
317
-
318
- var product_qty_input = jQuery( 'input[name=quantity\\[' + productdata.data( 'gtm4wp_product_id' ) + '\\]]' );
319
  if ( product_qty_input.length > 0 ) {
320
- product_qty = product_qty_input.val();
321
  } else {
322
- return;
323
  }
324
 
325
  if ( 0 == product_qty ) {
326
- return;
327
  }
328
 
329
- var product_data = {
330
- 'id': gtm4wp_use_sku_instead ? productdata.data( 'gtm4wp_product_sku' ) : productdata.data( 'gtm4wp_product_id' ),
331
- 'name': productdata.data( 'gtm4wp_product_name' ),
332
- 'price': productdata.data( 'gtm4wp_product_price' ),
333
- 'category': productdata.data( 'gtm4wp_product_cat' ),
334
  'quantity': product_qty,
335
- 'stocklevel': productdata.data( 'gtm4wp_product_stocklevel' ),
336
- 'brand': productdata.data( 'gtm4wp_product_brand' )
337
  };
338
 
339
  products.push( product_data );
@@ -342,7 +553,7 @@ jQuery(function() {
342
  });
343
 
344
  if ( 0 == products.length ) {
345
- return;
346
  }
347
 
348
  // fire ga3 version
@@ -366,14 +577,14 @@ jQuery(function() {
366
  }
367
  });
368
  } else {
369
- var product_data = {
370
- 'id': gtm4wp_use_sku_instead ? jQuery( '[name=gtm4wp_sku]', product_form ).val() : jQuery( '[name=gtm4wp_id]', product_form ).val(),
371
- 'name': jQuery( '[name=gtm4wp_name]', product_form ).val(),
372
- 'price': jQuery( '[name=gtm4wp_price]', product_form ).val(),
373
- 'category': jQuery( '[name=gtm4wp_category]', product_form ).val(),
374
- 'quantity': jQuery( '[name=quantity]', product_form ).val(),
375
- 'stocklevel': jQuery( '[name=gtm4wp_stocklevel]', product_form ).val(),
376
- 'brand': jQuery( '[name=gtm4wp_brand]', product_form ).val()
377
  };
378
 
379
  // fire ga3 version
@@ -400,36 +611,40 @@ jQuery(function() {
400
  });
401
 
402
  // track remove links in mini cart widget and on cart page
403
- jQuery( document ).on( 'click', '.mini_cart_item a.remove,.product-remove a.remove', function() {
404
- var productdata = jQuery( this );
 
 
 
 
405
 
406
- var qty = 0;
407
- var qty_element = jQuery( this ).closest( '.cart_item' ).find( '.product-quantity input.qty' );
408
- if ( qty_element.length === 0 ) {
409
- qty_element = jQuery( this ).closest( '.mini_cart_item' ).find( '.quantity' );
410
- if ( qty_element.length > 0 ) {
411
- qty = parseInt( qty_element.text() );
412
 
413
  if ( Number.isNaN( qty ) ) {
414
  qty = 0;
415
  }
416
  }
417
  } else {
418
- qty = qty_element.val();
419
  }
420
 
421
  if ( qty === 0 ) {
422
  return true;
423
  }
424
 
425
- var product_data = {
426
- 'name': productdata.data( 'gtm4wp_product_name' ),
427
- 'id': productdata.data( 'gtm4wp_product_id' ),
428
- 'price': productdata.data( 'gtm4wp_product_price' ),
429
- 'category': productdata.data( 'gtm4wp_product_cat' ),
430
- 'variant': productdata.data( 'gtm4wp_product_variant' ),
431
- 'stocklevel': productdata.data( 'gtm4wp_product_stocklevel' ),
432
- 'brand': productdata.data( 'gtm4wp_product_brand' ),
433
  'quantity': qty
434
  };
435
 
@@ -456,84 +671,102 @@ jQuery(function() {
456
  });
457
 
458
  // track clicks in product lists
459
- jQuery( document ).on( 'click', '.products li:not(.product-category) a:not(.add_to_cart_button):not(.quick-view-button),.products>div:not(.product-category) a:not(.add_to_cart_button):not(.quick-view-button),.widget-product-item,.woocommerce-grouped-product-list-item__label a', function( event ) {
 
 
 
 
 
460
  // do nothing if GTM is blocked for some reason
461
  if ( 'undefined' == typeof google_tag_manager ) {
462
  return true;
463
  }
464
 
465
- var temp_selector = jQuery( this ).closest( '.product' );
466
- var dom_productdata = '';
467
 
468
- if ( temp_selector.length > 0 ) {
469
- dom_productdata = temp_selector.find( '.gtm4wp_productdata' );
 
 
 
 
 
 
 
470
 
471
  } else {
472
- temp_selector = jQuery( this ).closest( '.products li' );
473
 
474
- if ( temp_selector.length > 0 ) {
475
- dom_productdata = temp_selector.find( '.gtm4wp_productdata' );
476
 
477
  } else {
478
- temp_selector = jQuery( this ).closest( '.products>div' );
479
 
480
- if ( temp_selector.length > 0 ) {
481
- dom_productdata = temp_selector.find( '.gtm4wp_productdata' );
482
 
483
  } else {
484
- temp_selector = jQuery( this ).closest( '.woocommerce-grouped-product-list-item__label' );
485
 
486
- if ( temp_selector.length > 0 ) {
487
- dom_productdata = temp_selector.find( '.gtm4wp_productdata' );
488
  } else {
489
- dom_productdata = jQuery( this );
490
  }
491
  }
492
  }
493
  }
494
 
495
- if ( ( 'undefined' == typeof dom_productdata.data( 'gtm4wp_product_id' ) ) || ( '' == dom_productdata.data( 'gtm4wp_product_id' ) ) ) {
496
  return true;
497
  }
498
 
499
  // only act on links pointing to the product detail page
500
- if ( dom_productdata.data( 'gtm4wp_product_url' ) != jQuery( this ).attr( 'href' ) ) {
501
  return true;
502
  }
503
 
504
- var ctrl_key_pressed = event.ctrlKey || event.metaKey;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505
 
506
- event.preventDefault();
507
  if ( ctrl_key_pressed ) {
508
  // we need to open the new tab/page here so that popup blocker of the browser doesn't block our code
509
- var productpage_window = window.open( 'about:blank', '_blank' );
510
  }
511
 
512
- var product_data = {
513
- 'id': dom_productdata.data( 'gtm4wp_product_id' ),
514
- 'name': dom_productdata.data( 'gtm4wp_product_name' ),
515
- 'price': dom_productdata.data( 'gtm4wp_product_price' ),
516
- 'category': dom_productdata.data( 'gtm4wp_product_cat' ),
517
- 'stocklevel': dom_productdata.data( 'gtm4wp_product_stocklevel' ),
518
- 'brand': dom_productdata.data( 'gtm4wp_product_brand' ),
519
- 'position': dom_productdata.data( 'gtm4wp_product_listposition' )
520
- };
521
-
522
  // fire ga3 version
523
  window[ gtm4wp_datalayer_name ].push({
524
  'event': 'gtm4wp.productClickEEC',
525
  'ecommerce': {
526
  'currencyCode': gtm4wp_currency,
527
  'click': {
528
- 'actionField': {'list': dom_productdata.data( 'gtm4wp_productlist_name' )},
529
  'products': [ product_data ]
530
  }
531
  },
532
- 'eventCallback': function() {
533
-
534
- // do not fire this event multiple times
535
- if ( window[ "gtm4wp_select_item_" + product_data.id ] ) {
536
- return;
537
  }
538
 
539
  // fire ga4 version
@@ -544,25 +777,23 @@ jQuery(function() {
544
  'items': [ gtm4wp_map_eec_to_ga4( product_data ) ]
545
  },
546
  'eventCallback': function() {
547
-
548
  if ( ctrl_key_pressed && productpage_window ) {
549
- productpage_window.location.href= dom_productdata.data( 'gtm4wp_product_url' );
550
  } else {
551
- document.location.href = dom_productdata.data( 'gtm4wp_product_url' );
552
  }
553
 
554
  },
555
  'eventTimeout': 2000
556
  });
557
-
558
- window[ "gtm4wp_select_item_" + product_data.id ] = true;
559
-
560
  },
561
  'eventTimeout': 2000
562
  });
563
  });
564
 
565
  // track variable products on their detail pages
 
 
566
  jQuery( document ).on( 'found_variation', function( event, product_variation ) {
567
  if ( "undefined" == typeof product_variation ) {
568
  // some ither plugins trigger this event without variation data
@@ -574,17 +805,17 @@ jQuery(function() {
574
  return;
575
  }
576
 
577
- var product_form = event.target;
578
- var product_variant_id = jQuery( '[name=variation_id]', product_form );
579
- var product_id = jQuery( '[name=gtm4wp_id]', product_form ).val();
580
- var product_name = jQuery( '[name=gtm4wp_name]', product_form ).val();
581
- var product_sku = jQuery( '[name=gtm4wp_sku]', product_form ).val();
582
- var product_category = jQuery( '[name=gtm4wp_category]', product_form ).val();
583
- var product_price = jQuery( '[name=gtm4wp_price]', product_form ).val();
584
- var product_stocklevel = jQuery( '[name=gtm4wp_stocklevel]', product_form ).val();
585
- var product_brand = jQuery( '[name=gtm4wp_brand]', product_form ).val();
586
-
587
- var current_product_detail_data = {
588
  name: product_name,
589
  id: 0,
590
  price: 0,
@@ -600,11 +831,11 @@ jQuery(function() {
600
  }
601
  current_product_detail_data.price = product_variation.display_price;
602
 
603
- var _tmp = [];
604
- for( var attrib_key in product_variation.attributes ) {
605
- _tmp.push( product_variation.attributes[ attrib_key ] );
606
  }
607
- current_product_detail_data.variant = _tmp.join(',');
608
  gtm4wp_last_selected_product_variation = current_product_detail_data;
609
 
610
  // fire ga3 version
@@ -626,6 +857,7 @@ jQuery(function() {
626
  'event': 'view_item',
627
  'ecommerce': {
628
  'currency': gtm4wp_currency,
 
629
  'items': [ gtm4wp_map_eec_to_ga4( current_product_detail_data ) ]
630
  }
631
  });
@@ -637,48 +869,90 @@ jQuery(function() {
637
  jQuery( '.variations select' ).trigger( 'change' );
638
 
639
  // initiate codes in WooCommere Quick View
 
 
640
  jQuery( document ).ajaxSuccess( function( event, xhr, settings ) {
641
  if(typeof settings !== 'undefined') {
642
  if (settings.url.indexOf( 'wc-api=WC_Quick_View' ) > -1 ) {
643
- setTimeout( function() {
644
- jQuery( ".woocommerce.quick-view" ).parent().find( "script" ).each( function(i) {
645
- eval( jQuery( this ).text() );
646
- });
 
 
 
 
 
 
 
 
 
 
647
  }, 500);
648
  }
649
  }
650
  });
651
 
652
  // codes for enhanced ecommerce events on cart page
653
- if ( is_cart ) {
654
- jQuery( document ).on( 'click', '[name=update_cart]', function() {
 
 
 
 
 
 
 
 
 
 
 
655
  gtm4wp_handle_cart_qty_change();
656
  });
657
 
658
- jQuery( document ).on( 'keypress', '.woocommerce-cart-form input[type=number]', function() {
 
 
 
 
 
 
 
 
 
 
 
659
  gtm4wp_handle_cart_qty_change();
660
  });
661
  }
662
 
663
  // codes for enhanced ecommerce events on checkout page
664
- if ( is_checkout ) {
665
  window.gtm4wp_checkout_step_offset = window.gtm4wp_checkout_step_offset || 0;
666
  window.gtm4wp_checkout_value = window.gtm4wp_checkout_value || 0;
667
  window.gtm4wp_checkout_products = window.gtm4wp_checkout_products || [];
668
  window.gtm4wp_checkout_products_ga4 = window.gtm4wp_checkout_products_ga4 || [];
669
 
670
- var gtm4wp_shipping_payment_method_step_offset = window.gtm4wp_needs_shipping_address ? 0 : -1;
671
- var gtm4wp_checkout_step_fired = []; // step 1 will be the billing section which is reported during pageload, no need to handle here
672
-
673
  // this checkout step is not reported to GA4 as currently there is no option to report in-between custom steps
674
- jQuery( document ).on( 'blur', 'input[name^=shipping_]:not(input[name^=shipping_method])', function() {
 
 
 
 
 
 
 
 
 
 
 
675
  // do not report checkout step if already reported
676
  if ( gtm4wp_checkout_step_fired.indexOf( 'shipping' ) > -1 ) {
677
  return;
678
  }
679
 
680
  // do not report checkout step if user is traversing through the section without filling in any data
681
- if ( jQuery( this ).val().trim() == '' ) {
682
  return;
683
  }
684
 
@@ -698,150 +972,89 @@ jQuery(function() {
698
  gtm4wp_checkout_step_fired.push( 'shipping' );
699
  });
700
 
701
- jQuery( document ).on( 'change', 'input[name^=shipping_method]', function() {
702
- // do not report checkout step if already reported
703
- if ( gtm4wp_checkout_step_fired.indexOf( 'shipping_method' ) > -1 ) {
704
- return;
705
- }
706
 
707
- // do not fire event during page load
708
- if ( 'complete' != document.readyState ) {
709
- return;
710
  }
711
 
712
- var shipping_tier = '(shipping tier not found)';
713
- var shipping_el = jQuery( 'input[name^=shipping_method]:checked' );
714
- if ( shipping_el.length == 0 ) {
715
- shipping_el = jQuery( 'input[name^=shipping_method]:first' );
716
- }
717
- if ( shipping_el.length > 0 ) {
718
- shipping_tier = shipping_el.val();
719
  }
720
 
721
- // fire ga3 version
722
- window[ gtm4wp_datalayer_name ].push({
723
- 'event': 'gtm4wp.checkoutStepEEC',
724
- 'ecommerce': {
725
- 'currencyCode': gtm4wp_currency,
726
- 'checkout': {
727
- 'actionField': {
728
- 'step': 3 + window.gtm4wp_checkout_step_offset + gtm4wp_shipping_payment_method_step_offset
729
- },
730
- 'products': window.gtm4wp_checkout_products
731
- }
732
- }
733
- });
734
-
735
- // fire ga4 version
736
- window[ gtm4wp_datalayer_name ].push({
737
- 'event': 'add_shipping_info',
738
- 'ecommerce': {
739
- 'currency': gtm4wp_currency,
740
- 'shipping_tier': shipping_tier,
741
- 'value': window.gtm4wp_checkout_value,
742
- 'items': window.gtm4wp_checkout_products_ga4
743
- }
744
- });
745
-
746
- gtm4wp_checkout_step_fired.push( 'shipping_method' );
747
  });
748
 
749
- jQuery( document ).on( 'change', 'input[name=payment_method]', function() {
750
- // do not report checkout step if already reported
751
- if ( gtm4wp_checkout_step_fired.indexOf( 'payment_method' ) > -1 ) {
752
- return;
753
- }
754
 
755
- // do not fire event during page load
756
- if ( 'complete' != document.readyState ) {
757
- return;
758
  }
759
 
760
- var payment_type = '(payment type not found)';
761
- var payment_el = jQuery( '.payment_methods input:checked' );
762
- if ( payment_el.length == 0 ) {
763
- payment_el = jQuery( 'input[name^=payment_method]:first' );
764
- }
765
- if ( payment_el.length > 0 ) {
766
- payment_type = payment_el.val();
767
  }
768
 
769
- // fire ga3 version
770
- window[ gtm4wp_datalayer_name ].push({
771
- 'event': 'gtm4wp.checkoutStepEEC',
772
- 'ecommerce': {
773
- 'currencyCode': gtm4wp_currency,
774
- 'checkout': {
775
- 'actionField': {
776
- 'step': 4 + window.gtm4wp_checkout_step_offset + gtm4wp_shipping_payment_method_step_offset
777
- },
778
- 'products': window.gtm4wp_checkout_products
779
- }
780
- }
781
- });
782
 
783
- // fire ga4 version
784
- window[ gtm4wp_datalayer_name ].push({
785
- 'event': 'add_payment_info',
786
- 'ecommerce': {
787
- 'currency': gtm4wp_currency,
788
- 'payment_type': payment_type,
789
- 'value': window.gtm4wp_checkout_value,
790
- 'items': window.gtm4wp_checkout_products_ga4
791
- }
792
- });
793
 
794
- gtm4wp_checkout_step_fired.push( 'payment_method' );
795
- });
 
 
 
 
 
 
796
 
797
- jQuery( 'form[name=checkout]' ).on( 'submit', function() {
798
  if ( gtm4wp_checkout_step_fired.indexOf( 'shipping_method' ) == -1 ) {
799
  // shipping methods are not visible if only one is available
800
  // and if the user has already a pre-selected method, no click event will fire to report the checkout step
801
- var selected_shipping_method = jQuery( 'input[name^=shipping_method]:checked' );
802
- if ( selected_shipping_method.length == 0 ) {
803
- selected_shipping_method = jQuery( 'input[name^=shipping_method]:first' );
804
- }
805
- if ( selected_shipping_method.length > 0 ) {
806
- selected_shipping_method.trigger( 'change' );
807
- }
808
  }
809
 
810
  if ( gtm4wp_checkout_step_fired.indexOf( 'payment_method' ) == -1 ) {
811
  // if the user has already a pre-selected method, no click event will fire to report the checkout step
812
- jQuery( 'input[name=payment_method]:checked' ).trigger( 'change' );
813
  }
814
 
815
- var shipping_el = jQuery( 'input[name^=shipping_method]:checked' );
816
- if ( shipping_el.length == 0 ) {
817
- shipping_el = jQuery( 'input[name^=shipping_method]:first' );
818
  }
819
- if ( shipping_el.length > 0 ) {
820
  window[ gtm4wp_datalayer_name ].push({
821
  'event': 'gtm4wp.checkoutOptionEEC',
822
  'ecommerce': {
823
  'checkout_option': {
824
  'actionField': {
825
  'step': 3 + window.gtm4wp_checkout_step_offset + gtm4wp_shipping_payment_method_step_offset,
826
- 'option': 'Shipping: ' + shipping_el.val()
827
  }
828
  }
829
  }
830
  });
831
  }
832
 
833
- var payment_el = jQuery( '.payment_methods input:checked' );
834
- if ( payment_el.length == 0 ) {
835
- payment_el = jQuery( 'input[name^=payment_method]:first' );
836
  }
837
- if ( payment_el.length > 0 ) {
838
  window[ gtm4wp_datalayer_name ].push({
839
  'event': 'gtm4wp.checkoutOptionEEC',
840
  'ecommerce': {
841
  'checkout_option': {
842
  'actionField': {
843
  'step': 4 + window.gtm4wp_checkout_step_offset + gtm4wp_shipping_payment_method_step_offset,
844
- 'option': 'Payment: ' + payment_el.val()
845
  }
846
  }
847
  }
@@ -851,7 +1064,10 @@ jQuery(function() {
851
  }
852
 
853
  // codes for Google Ads dynamic remarketing
854
- if ( window.gtm4wp_remarketing&& !is_cart && !is_checkout ) {
 
 
 
855
  if ( jQuery( '.gtm4wp_productdata' ).length > 0 ) {
856
  for( var i=0; i<window[ gtm4wp_datalayer_name ].length; i++ ) {
857
  if ( window[ gtm4wp_datalayer_name ][ i ][ 'ecomm_prodid' ] ) {
@@ -885,15 +1101,16 @@ jQuery(function() {
885
  'event': 'view_item',
886
  'ecommerce': {
887
  'currency': gtm4wp_currency,
 
888
  'items': [ gtm4wp_map_eec_to_ga4( item.ecommerce.detail.products[0] ) ]
889
  }
890
  });
891
  }
892
 
893
- if ( item && item.ecommerce && ( item.ecommerce.cart || (item.ecommerce.checkout && is_cart) ) ) {
894
- var source_products = item.ecommerce.cart || item.ecommerce.checkout.products;
895
- var ga4_products = [];
896
- var sum_value = 0;
897
 
898
  source_products.forEach(function( product ) {
899
  ga4_products.push( gtm4wp_map_eec_to_ga4( product ) );
@@ -910,9 +1127,9 @@ jQuery(function() {
910
  });
911
  }
912
 
913
- if ( item && item.ecommerce && item.ecommerce.checkout && !is_cart ) {
914
- var ga4_products = [];
915
- var sum_value = 0;
916
 
917
  item.ecommerce.checkout.products.forEach(function( product ) {
918
  ga4_products.push( gtm4wp_map_eec_to_ga4( product ) );
@@ -931,8 +1148,8 @@ jQuery(function() {
931
 
932
  // present if product is readded into cart just after removel
933
  if ( item && item.ecommerce && item.ecommerce.add ) {
934
- var ga4_products = [];
935
- var sum_value = 0;
936
 
937
  item.ecommerce.add.products.forEach(function( product ) {
938
  ga4_products.push( gtm4wp_map_eec_to_ga4( product ) );
@@ -950,7 +1167,7 @@ jQuery(function() {
950
  }
951
 
952
  if ( item && item.ecommerce && item.ecommerce.purchase ) {
953
- var ga4_products = [];
954
  item.ecommerce.purchase.products.forEach(function( product ) {
955
  ga4_products.push( gtm4wp_map_eec_to_ga4( product ) );
956
  });
1
+ window.gtm4wp_last_selected_product_variation;
2
+ window.gtm4wp_changedetail_fired_during_pageload=false;
3
+
4
+ window.gtm4wp_is_cart = false;
5
+ window.gtm4wp_is_checkout = false;
6
+ window.gtm4wp_checkout_step_fired = []; // step 1 will be the billing section which is reported during pageload, no need to handle here
7
+ window.gtm4wp_shipping_payment_method_step_offset = window.gtm4wp_needs_shipping_address ? 0 : -1;
8
+
9
+ window.gtm4wp_first_container_id = "";
10
 
11
  function gtm4wp_map_eec_to_ga4( productdata ) {
12
+ if ( !productdata ) {
13
  return;
14
  }
15
 
16
+ const category_path = productdata.category ? productdata.category : '';
17
+ const category_parts = category_path.toString().split('/');
18
 
19
  // default, required parameters
20
+ let ga4_product = {
21
  'item_id': productdata.id ? productdata.id : '',
22
  'item_name': productdata.name ? productdata.name : '',
23
  'item_brand': productdata.brand ? productdata.brand : '',
29
  ga4_product.item_category = category_parts[0];
30
  } else if ( category_parts.length > 1 ) {
31
  ga4_product.item_category = category_parts[0];
32
+ for( let i=1; i < Math.min( 5, category_parts.length ); i++ ) {
33
  ga4_product[ 'item_category_' + (i+1) ] = category_parts[i];
34
  }
35
  }
58
  }
59
 
60
  function gtm4wp_handle_cart_qty_change() {
61
+ document.querySelectorAll( '.product-quantity input.qty' ).forEach(function( qty_el ) {
62
+ const original_value = qty_el.defaultValue;
63
 
64
+ let current_value = parseInt( qty_el.value );
65
+ if ( isNaN( current_value ) ) {
66
+ current_value = original_value;
67
  }
68
 
69
+ // is quantity changed changed?
70
+ if ( original_value != current_value ) {
71
+ const productdata = qty_el.closest( '.cart_item' )?.querySelector( '.remove' );
72
+ if ( !productdata ) {
73
+ return;
74
+ }
75
+
76
+ let productprice = productdata.getAttribute( 'data-gtm4wp_product_price' );
77
 
78
  if ( typeof productprice == "string" ) {
79
  productprice = parseFloat( productprice );
84
  productprice = 0;
85
  }
86
 
87
+ // does the quantity increase?
88
+ if ( original_value < current_value ) {
89
+ // yes => handle add to cart event
90
+ const product_data = {
91
+ 'name': productdata.getAttribute( 'data-gtm4wp_product_name' ),
92
+ 'id': productdata.getAttribute( 'data-gtm4wp_product_id' ),
93
  'price': productprice.toFixed(2),
94
+ 'category': productdata.getAttribute( 'data-gtm4wp_product_cat' ),
95
+ 'variant': productdata.getAttribute( 'data-gtm4wp_product_variant' ),
96
+ 'stocklevel': productdata.getAttribute( 'data-gtm4wp_product_stocklevel' ),
97
+ 'brand': productdata.getAttribute( 'data-gtm4wp_product_brand' ),
98
+ 'quantity': current_value - original_value
99
  };
100
 
101
  // fire ga3 version
114
  'event': 'add_to_cart',
115
  'ecommerce': {
116
  'currency': gtm4wp_currency, // ga4 version
117
+ 'value': productprice.toFixed(2) * (current_value - original_value),
118
  'items': [ gtm4wp_map_eec_to_ga4( product_data ) ]
119
  }
120
  });
121
  } else {
122
+ // no => handle remove from cart event
123
+ const product_data = {
124
+ 'name': productdata.getAttribute( 'data-gtm4wp_product_name' ),
125
+ 'id': productdata.getAttribute( 'data-gtm4wp_product_id' ),
126
  'price': productprice.toFixed(2),
127
+ 'category': productdata.getAttribute( 'data-gtm4wp_product_cat' ),
128
+ 'variant': productdata.getAttribute( 'data-gtm4wp_product_variant' ),
129
+ 'stocklevel': productdata.getAttribute( 'data-gtm4wp_product_stocklevel' ),
130
+ 'brand': productdata.getAttribute( 'data-gtm4wp_product_brand' ),
131
+ 'quantity': original_value - current_value
132
  };
133
 
134
  // fire ga3 version
147
  'event': 'remove_from_cart',
148
  'ecommerce': {
149
  'currency': gtm4wp_currency,
150
+ 'value': productprice.toFixed(2) * (original_value - current_value),
151
  'items': [ gtm4wp_map_eec_to_ga4( product_data ) ]
152
  }
153
  });
156
  }); // end each qty field
157
  } // end gtm4wp_handle_cart_qty_change()
158
 
159
+ function gtm4wp_handle_payment_method_change() {
160
+ // do not report checkout step if already reported
161
+ if ( gtm4wp_checkout_step_fired.indexOf( 'payment_method' ) > -1 ) {
162
+ return;
163
+ }
164
+
165
+ // do not fire event during page load
166
+ if ( 'complete' != document.readyState ) {
167
+ return;
168
+ }
169
+
170
+ let payment_type = '(payment type not found)';
171
+ let payment_el = document.querySelector( '.payment_methods input:checked' );
172
+ if ( !payment_el ) {
173
+ payment_el = document.querySelector( 'input[name^=payment_method]' ); // select the first input element
174
+ }
175
+ if ( payment_el ) {
176
+ payment_type = payment_el.value;
177
+ }
178
+
179
+ // fire ga3 version
180
+ window[ gtm4wp_datalayer_name ].push({
181
+ 'event': 'gtm4wp.checkoutStepEEC',
182
+ 'ecommerce': {
183
+ 'currencyCode': gtm4wp_currency,
184
+ 'checkout': {
185
+ 'actionField': {
186
+ 'step': 4 + window.gtm4wp_checkout_step_offset + gtm4wp_shipping_payment_method_step_offset
187
+ },
188
+ 'products': window.gtm4wp_checkout_products
189
+ }
190
+ }
191
+ });
192
+
193
+ // fire ga4 version
194
+ window[ gtm4wp_datalayer_name ].push({
195
+ 'event': 'add_payment_info',
196
+ 'ecommerce': {
197
+ 'currency': gtm4wp_currency,
198
+ 'payment_type': payment_type,
199
+ 'value': window.gtm4wp_checkout_value,
200
+ 'items': window.gtm4wp_checkout_products_ga4
201
+ }
202
+ });
203
+
204
+ gtm4wp_checkout_step_fired.push( 'payment_method' );
205
+ } // end gtm4wp_handle_payment_method_change()
206
+
207
+ function gtm4wp_handle_shipping_method_change() {
208
+ // do not report checkout step if already reported
209
+ if ( gtm4wp_checkout_step_fired.indexOf( 'shipping_method' ) > -1 ) {
210
+ return;
211
+ }
212
+
213
+ // do not fire event during page load
214
+ if ( 'complete' != document.readyState ) {
215
+ return;
216
+ }
217
+
218
+ let shipping_tier = '(shipping tier not found)';
219
+ let shipping_el = document.querySelector( 'input[name^=shipping_method]:checked' );
220
+ if ( !shipping_el ) {
221
+ shipping_el = document.querySelector( 'input[name^=shipping_method]' ); // select the first input element
222
+ }
223
+ if ( shipping_el ) {
224
+ shipping_tier = shipping_el.value;
225
+ }
226
+
227
+ // fire ga3 version
228
+ window[ gtm4wp_datalayer_name ].push({
229
+ 'event': 'gtm4wp.checkoutStepEEC',
230
+ 'ecommerce': {
231
+ 'currencyCode': gtm4wp_currency,
232
+ 'checkout': {
233
+ 'actionField': {
234
+ 'step': 3 + window.gtm4wp_checkout_step_offset + gtm4wp_shipping_payment_method_step_offset
235
+ },
236
+ 'products': window.gtm4wp_checkout_products
237
+ }
238
+ }
239
+ });
240
+
241
+ // fire ga4 version
242
+ window[ gtm4wp_datalayer_name ].push({
243
+ 'event': 'add_shipping_info',
244
+ 'ecommerce': {
245
+ 'currency': gtm4wp_currency,
246
+ 'shipping_tier': shipping_tier,
247
+ 'value': window.gtm4wp_checkout_value,
248
+ 'items': window.gtm4wp_checkout_products_ga4
249
+ }
250
+ });
251
+
252
+ gtm4wp_checkout_step_fired.push( 'shipping_method' );
253
+ }
254
+
255
+ document.addEventListener( 'DOMContentLoaded', function() {
256
+ window.gtm4wp_is_cart = document.querySelector( 'body' )?.classList?.contains( 'woocommerce-cart' );
257
+ window.gtm4wp_is_checkout = document.querySelector( 'body' )?.classList?.contains( 'woocommerce-checkout' );
258
+
259
+ // loop through WC blocks to set proper listname and position parameters
260
+ const gtm4wp_product_block_names = {
261
+ 'wp-block-handpicked-products': {
262
+ 'displayname': 'Handpicked Products',
263
+ 'counter': 1
264
+ },
265
+ 'wp-block-product-best-sellers': {
266
+ 'displayname': 'Best Selling Products',
267
+ 'counter': 1
268
+ },
269
+ 'wp-block-product-category': {
270
+ 'displayname': 'Product Category List',
271
+ 'counter': 1
272
+ },
273
+ 'wp-block-product-new': {
274
+ 'displayname': 'New Products',
275
+ 'counter': 1
276
+ },
277
+ 'wp-block-product-on-sale': {
278
+ 'displayname': 'Sale Products',
279
+ 'counter': 1
280
+ },
281
+ 'wp-block-products-by-attribute': {
282
+ 'displayname': 'Products By Attribute',
283
+ 'counter': 1
284
+ },
285
+ 'wp-block-product-tag': {
286
+ 'displayname': 'Products By Tag',
287
+ 'counter': 1
288
+ },
289
+ 'wp-block-product-top-rated': {
290
+ 'displayname': 'Top Rated Products',
291
+ 'counter': 1
292
+ },
293
+ }
294
+ document.querySelectorAll( '.wc-block-grid .wc-block-grid__product' ).forEach( function( product_grid_item ) {
295
+
296
+ const product_grid_container = product_grid_item.closest( '.wc-block-grid' );
297
+ const product_data = product_grid_item.querySelector( '.gtm4wp_productdata' );
298
+
299
+ if ( product_grid_container && product_data ) {
300
+
301
+ const product_grid_container_classes = product_grid_container.classList;
302
+
303
+ if ( product_grid_container_classes ) {
304
+
305
+ for(let i in gtm4wp_product_block_names) {
306
+ if ( product_grid_container_classes.contains( i ) ) {
307
+ product_data.setAttribute("data-gtm4wp_productlist_name", gtm4wp_product_block_names[i].displayname);
308
+ product_data.setAttribute("data-gtm4wp_product_listposition", gtm4wp_product_block_names[i].counter);
309
+
310
+ gtm4wp_product_block_names[i].counter++;
311
+ }
312
+ }
313
+ }
314
+ }
315
+ });
316
 
317
  // track impressions of products in product lists
318
+ if ( document.querySelectorAll( '.gtm4wp_productdata,.widget-product-item' ).length > 0 ) {
319
+ let products = [];
320
+ let ga4_products = [];
321
+ let productprice = 0;
322
+ let product_data;
323
 
324
+ document.querySelectorAll( '.gtm4wp_productdata,.widget-product-item' ).forEach( function( dom_productdata ) {
325
+ productprice = dom_productdata.getAttribute( 'gtm4wp_product_price' );
 
326
 
327
  if ( typeof productprice == "string" ) {
328
  productprice = parseFloat( productprice );
334
  }
335
 
336
  product_data = {
337
+ 'name': dom_productdata.getAttribute( 'data-gtm4wp_product_name' ),
338
+ 'id': dom_productdata.getAttribute( 'data-gtm4wp_product_id' ),
339
  'price': productprice.toFixed(2),
340
+ 'category': dom_productdata.getAttribute( 'data-gtm4wp_product_cat' ),
341
+ 'position': dom_productdata.getAttribute( 'data-gtm4wp_product_listposition' ),
342
+ 'list': dom_productdata.getAttribute( 'data-gtm4wp_productlist_name' ),
343
+ 'stocklevel': dom_productdata.getAttribute( 'data-gtm4wp_product_stocklevel' ),
344
+ 'brand': dom_productdata.getAttribute( 'data-gtm4wp_product_brand' )
345
  };
346
+
347
  products.push(product_data);
348
  ga4_products.push( gtm4wp_map_eec_to_ga4( product_data ) );
349
  });
350
 
351
  if ( gtm4wp_product_per_impression > 0 ) {
352
  // Need to split the product submissions up into chunks in order to avoid the GA 8kb submission limit
353
+ let chunk
354
+ let ga4_chunk;
355
+
356
  while ( products.length ) {
357
  chunk = products.splice( 0, gtm4wp_product_per_impression );
358
  ga4_chunk = ga4_products.splice( 0, gtm4wp_product_per_impression );
401
  }
402
 
403
  // track add to cart events for simple products in product lists
404
+ document.addEventListener( 'click', function( e ) {
405
+ let event_target_element = e.target;
406
+
407
+ if ( !event_target_element ) {
408
+ // for some reason event target is not specificed
409
+ return true;
410
+ }
411
+
412
+ try {
413
+ if ( !event_target_element.closest( '.add_to_cart_button:not(.product_type_variable, .product_type_grouped, .single_add_to_cart_button)' ) ) {
414
+ return true;
415
+ }
416
+ } catch (e) {
417
+ // during beta testing, closest() sometimes threw SyntaxError which is thrown if selector is invalid. But the selector above should be valid in all cases
418
+ // assumption was that perhaps event_target_element was not set or not a proper DOM node for some reasons
419
+ return true;
420
+ }
421
+
422
+ const productdata = event_target_element.closest( '.product,.wc-block-grid__product' )?.querySelector( '.gtm4wp_productdata' );
423
+ if ( !productdata ) {
424
+ return true;
425
+ }
426
+
427
+ let productprice = productdata.getAttribute( 'data-gtm4wp_product_price' );
428
 
429
  if ( typeof productprice == "string" ) {
430
  productprice = parseFloat( productprice );
435
  productprice = 0;
436
  }
437
 
438
+ const product_data = {
439
+ 'name': productdata.getAttribute( 'data-gtm4wp_product_name' ),
440
+ 'id': productdata.getAttribute( 'data-gtm4wp_product_id' ),
441
  'price': productprice.toFixed(2),
442
+ 'category': productdata.getAttribute( 'data-gtm4wp_product_cat' ),
443
+ 'stocklevel': productdata.getAttribute( 'data-gtm4wp_product_stocklevel' ),
444
+ 'brand': productdata.getAttribute( 'data-gtm4wp_product_brand' ),
445
  'quantity': 1
446
  };
447
 
468
  });
469
 
470
  // track add to cart events for products on product detail pages
471
+ document.addEventListener( 'click', function( e ) {
472
+ let event_target_element = e.target;
473
+
474
+ if ( !event_target_element ) {
475
+ // for some reason event target is not specificed
476
+ return true;
477
+ }
478
+
479
+ try {
480
+ if ( !event_target_element.closest( '.single_add_to_cart_button:not(.disabled)' ) ) {
481
+ return true;
482
+ }
483
+ } catch (e) {
484
+ // during beta testing, closest() sometimes threw SyntaxError which is thrown if selector is invalid. But the selector above should be valid in all cases
485
+ // assumption was that perhaps event_target_element was not set or not a proper DOM node for some reasons
486
+ return true;
487
+ }
488
+
489
+ const product_form = event_target_element.closest( 'form.cart' );
490
+ if ( !product_form ) {
491
+ return true;
492
+ }
493
+
494
+ let product_variant_id = product_form.querySelectorAll( '[name=variation_id]' );
495
+ let product_is_grouped = product_form.classList?.contains( 'grouped_form' );
496
 
497
  if ( product_variant_id.length > 0 ) {
498
  if ( gtm4wp_last_selected_product_variation ) {
499
+ gtm4wp_last_selected_product_variation.quantity = product_form.querySelector( '[name=quantity]' )?.value || 1;
500
 
501
  // fire ga3 version
502
  window[ gtm4wp_datalayer_name ].push({
520
  });
521
  }
522
  } else if ( product_is_grouped ) {
523
+ const products_in_group = document.querySelectorAll( '.grouped_form .gtm4wp_productdata' );
524
+ let products = [];
525
+ let ga4_products = [];
526
+ let sum_value = 0;
527
 
528
+ products_in_group.forEach( function( dom_productdata ) {
529
+ const product_qty_input = document.querySelectorAll( 'input[name=quantity\\[' + dom_productdata.getAttribute( 'data-gtm4wp_product_id' ) + '\\]]' );
 
 
530
  if ( product_qty_input.length > 0 ) {
531
+ product_qty = product_qty_input[0]?.value || 1;
532
  } else {
533
+ return true;
534
  }
535
 
536
  if ( 0 == product_qty ) {
537
+ return true;
538
  }
539
 
540
+ const product_data = {
541
+ 'id': gtm4wp_use_sku_instead ? dom_productdata.getAttribute( 'data-gtm4wp_product_sku' ) : dom_productdata.getAttribute( 'data-gtm4wp_product_id' ),
542
+ 'name': dom_productdata.getAttribute( 'data-gtm4wp_product_name' ),
543
+ 'price': dom_productdata.getAttribute( 'data-gtm4wp_product_price' ),
544
+ 'category': dom_productdata.getAttribute( 'data-gtm4wp_product_cat' ),
545
  'quantity': product_qty,
546
+ 'stocklevel': dom_productdata.getAttribute( 'data-gtm4wp_product_stocklevel' ),
547
+ 'brand': dom_productdata.getAttribute( 'data-gtm4wp_product_brand' )
548
  };
549
 
550
  products.push( product_data );
553
  });
554
 
555
  if ( 0 == products.length ) {
556
+ return true;
557
  }
558
 
559
  // fire ga3 version
577
  }
578
  });
579
  } else {
580
+ const product_data = {
581
+ 'id': gtm4wp_use_sku_instead ? product_form.querySelector( '[name=gtm4wp_sku]' )?.value : product_form.querySelector( '[name=gtm4wp_id]' )?.value,
582
+ 'name': product_form.querySelector( '[name=gtm4wp_name]' )?.value,
583
+ 'price': product_form.querySelector( '[name=gtm4wp_price]' )?.value,
584
+ 'category': product_form.querySelector( '[name=gtm4wp_category]' )?.value,
585
+ 'quantity': product_form.querySelector( '[name=quantity]' )?.value,
586
+ 'stocklevel': product_form.querySelector( '[name=gtm4wp_stocklevel]' )?.value,
587
+ 'brand': product_form.querySelector( '[name=gtm4wp_brand]' )?.value
588
  };
589
 
590
  // fire ga3 version
611
  });
612
 
613
  // track remove links in mini cart widget and on cart page
614
+ document.addEventListener( 'click', function( e ) {
615
+ const dom_productdata = e.target;
616
+
617
+ if ( !dom_productdata.closest( '.mini_cart_item a.remove,.product-remove a.remove' ) ) {
618
+ return true;
619
+ }
620
 
621
+ let qty = 0;
622
+ let qty_element = dom_productdata.closest( '.cart_item' )?.querySelectorAll( '.product-quantity input.qty' );
623
+ if ( !qty_element || ( qty_element.length === 0 ) ) {
624
+ qty_element = dom_productdata.closest( '.mini_cart_item' )?.querySelectorAll( '.quantity' );
625
+ if ( qty_element && ( qty_element.length > 0 ) ) {
626
+ qty = parseInt( qty_element[0].textContent );
627
 
628
  if ( Number.isNaN( qty ) ) {
629
  qty = 0;
630
  }
631
  }
632
  } else {
633
+ qty = qty_element[0].value;
634
  }
635
 
636
  if ( qty === 0 ) {
637
  return true;
638
  }
639
 
640
+ const product_data = {
641
+ 'name': dom_productdata.getAttribute( 'data-gtm4wp_product_name' ),
642
+ 'id': dom_productdata.getAttribute( 'data-gtm4wp_product_id' ),
643
+ 'price': dom_productdata.getAttribute( 'data-gtm4wp_product_price' ),
644
+ 'category': dom_productdata.getAttribute( 'data-gtm4wp_product_cat' ),
645
+ 'variant': dom_productdata.getAttribute( 'data-gtm4wp_product_variant' ),
646
+ 'stocklevel': dom_productdata.getAttribute( 'data-gtm4wp_product_stocklevel' ),
647
+ 'brand': dom_productdata.getAttribute( 'data-gtm4wp_product_brand' ),
648
  'quantity': qty
649
  };
650
 
671
  });
672
 
673
  // track clicks in product lists
674
+ let productlist_item_selector = '.products li:not(.product-category) a:not(.add_to_cart_button):not(.quick-view-button),'
675
+ +'.wc-block-grid__products li:not(.product-category) a:not(.add_to_cart_button):not(.quick-view-button),'
676
+ +'.products>div:not(.product-category) a:not(.add_to_cart_button):not(.quick-view-button),'
677
+ +'.widget-product-item,'
678
+ +'.woocommerce-grouped-product-list-item__label a'
679
+ document.addEventListener( 'click', function( e ) {
680
  // do nothing if GTM is blocked for some reason
681
  if ( 'undefined' == typeof google_tag_manager ) {
682
  return true;
683
  }
684
 
685
+ const event_target_element = e.target;
686
+ const matching_link_element = event_target_element.closest( productlist_item_selector );
687
 
688
+ if ( !matching_link_element ) {
689
+ return true;
690
+ }
691
+
692
+ let temp_selector = event_target_element.closest( '.product,.wc-block-grid__product' );
693
+ let dom_productdata;
694
+
695
+ if ( temp_selector ) {
696
+ dom_productdata = temp_selector.querySelector( '.gtm4wp_productdata' );
697
 
698
  } else {
699
+ temp_selector = event_target_element.closest( '.products li' );
700
 
701
+ if ( temp_selector ) {
702
+ dom_productdata = temp_selector.querySelector( '.gtm4wp_productdata' );
703
 
704
  } else {
705
+ temp_selector = event_target_element.closest( '.products>div' );
706
 
707
+ if ( temp_selector ) {
708
+ dom_productdata = temp_selector.querySelector( '.gtm4wp_productdata' );
709
 
710
  } else {
711
+ temp_selector = event_target_element.closest( '.woocommerce-grouped-product-list-item__label' );
712
 
713
+ if ( temp_selector ) {
714
+ dom_productdata = temp_selector.querySelector( '.gtm4wp_productdata' );
715
  } else {
716
+ dom_productdata = event_target_element;
717
  }
718
  }
719
  }
720
  }
721
 
722
+ if ( ( 'undefined' == typeof dom_productdata.getAttribute( 'data-gtm4wp_product_id' ) ) || ( '' == dom_productdata.getAttribute( 'data-gtm4wp_product_id' ) ) ) {
723
  return true;
724
  }
725
 
726
  // only act on links pointing to the product detail page
727
+ if ( dom_productdata.getAttribute( 'data-gtm4wp_product_url' ) != matching_link_element.getAttribute( 'href' ) ) {
728
  return true;
729
  }
730
 
731
+ const product_data = {
732
+ 'id': dom_productdata.getAttribute( 'data-gtm4wp_product_id' ),
733
+ 'name': dom_productdata.getAttribute( 'data-gtm4wp_product_name' ),
734
+ 'price': dom_productdata.getAttribute( 'data-gtm4wp_product_price' ),
735
+ 'category': dom_productdata.getAttribute( 'data-gtm4wp_product_cat' ),
736
+ 'stocklevel': dom_productdata.getAttribute( 'data-gtm4wp_product_stocklevel' ),
737
+ 'brand': dom_productdata.getAttribute( 'data-gtm4wp_product_brand' ),
738
+ 'position': dom_productdata.getAttribute( 'data-gtm4wp_product_listposition' )
739
+ };
740
+
741
+ for (let i in window.google_tag_manager) {
742
+ if (i.substring(0,4).toLowerCase() == "gtm-") {
743
+ window.gtm4wp_first_container_id = i;
744
+ break;
745
+ }
746
+ }
747
+
748
+ const ctrl_key_pressed = e.ctrlKey || e.metaKey;
749
 
750
+ e.preventDefault();
751
  if ( ctrl_key_pressed ) {
752
  // we need to open the new tab/page here so that popup blocker of the browser doesn't block our code
753
+ window.productpage_window = window.open( 'about:blank', '_blank' );
754
  }
755
 
 
 
 
 
 
 
 
 
 
 
756
  // fire ga3 version
757
  window[ gtm4wp_datalayer_name ].push({
758
  'event': 'gtm4wp.productClickEEC',
759
  'ecommerce': {
760
  'currencyCode': gtm4wp_currency,
761
  'click': {
762
+ 'actionField': {'list': dom_productdata.getAttribute( 'data-gtm4wp_productlist_name' )},
763
  'products': [ product_data ]
764
  }
765
  },
766
+ 'eventCallback': function( container_id ) {
767
+ if (window.gtm4wp_first_container_id != container_id) {
768
+ // only call this for the first loaded container
769
+ return true;
 
770
  }
771
 
772
  // fire ga4 version
777
  'items': [ gtm4wp_map_eec_to_ga4( product_data ) ]
778
  },
779
  'eventCallback': function() {
 
780
  if ( ctrl_key_pressed && productpage_window ) {
781
+ productpage_window.location.href = dom_productdata.getAttribute( 'data-gtm4wp_product_url' );
782
  } else {
783
+ document.location.href = dom_productdata.getAttribute( 'data-gtm4wp_product_url' );
784
  }
785
 
786
  },
787
  'eventTimeout': 2000
788
  });
 
 
 
789
  },
790
  'eventTimeout': 2000
791
  });
792
  });
793
 
794
  // track variable products on their detail pages
795
+ // currently, we need to use jQuery here since WooCommerce is firing this event using jQuery
796
+ // that can not be catched using vanilla JS
797
  jQuery( document ).on( 'found_variation', function( event, product_variation ) {
798
  if ( "undefined" == typeof product_variation ) {
799
  // some ither plugins trigger this event without variation data
805
  return;
806
  }
807
 
808
+ const product_form = event.target;
809
+ const product_variant_id = product_form.querySelector( '[name=variation_id]' )?.value;
810
+ const product_id = product_form.querySelector( '[name=gtm4wp_id]' )?.value;
811
+ const product_name = product_form.querySelector( '[name=gtm4wp_name]' )?.value;
812
+ const product_sku = product_form.querySelector( '[name=gtm4wp_sku]' )?.value;
813
+ const product_category = product_form.querySelector( '[name=gtm4wp_category]' )?.value;
814
+ const product_price = product_form.querySelector( '[name=gtm4wp_price]' )?.value;
815
+ const product_stocklevel = product_form.querySelector( '[name=gtm4wp_stocklevel]' )?.value;
816
+ const product_brand = product_form.querySelector( '[name=gtm4wp_brand]' )?.value;
817
+
818
+ let current_product_detail_data = {
819
  name: product_name,
820
  id: 0,
821
  price: 0,
831
  }
832
  current_product_detail_data.price = product_variation.display_price;
833
 
834
+ let product_variation_attribute_values = [];
835
+ for( let attrib_key in product_variation.attributes ) {
836
+ product_variation_attribute_values.push( product_variation.attributes[ attrib_key ] );
837
  }
838
+ current_product_detail_data.variant = product_variation_attribute_values.join(',');
839
  gtm4wp_last_selected_product_variation = current_product_detail_data;
840
 
841
  // fire ga3 version
857
  'event': 'view_item',
858
  'ecommerce': {
859
  'currency': gtm4wp_currency,
860
+ 'value': current_product_detail_data.price,
861
  'items': [ gtm4wp_map_eec_to_ga4( current_product_detail_data ) ]
862
  }
863
  });
869
  jQuery( '.variations select' ).trigger( 'change' );
870
 
871
  // initiate codes in WooCommere Quick View
872
+ // currently, we need to use jQuery here since WooCommerce Quick View is showing the popup using
873
+ // jQuery AJAX calls that can not be catched using vanilla JS
874
  jQuery( document ).ajaxSuccess( function( event, xhr, settings ) {
875
  if(typeof settings !== 'undefined') {
876
  if (settings.url.indexOf( 'wc-api=WC_Quick_View' ) > -1 ) {
877
+ setTimeout( function() {
878
+
879
+ const dl_data = document.querySelector('#gtm4wp_quickview_data');
880
+ if ( dl_data && dl_data.dataset && dl_data.dataset.gtm4wp_datalayer ) {
881
+ try {
882
+ const dl_data_obj = JSON.parse( dl_data.dataset.gtm4wp_datalayer );
883
+ if ( dl_data_obj && window.dataLayer ) {
884
+ window.dataLayer.push(dl_data_obj);
885
+ }
886
+ } catch(e) {
887
+ console && console.error && console.error( e.message );
888
+ }
889
+ }
890
+
891
  }, 500);
892
  }
893
  }
894
  });
895
 
896
  // codes for enhanced ecommerce events on cart page
897
+ if ( gtm4wp_is_cart ) {
898
+ document.addEventListener( 'click', function( e ) {
899
+ let event_target_element = e.target;
900
+
901
+ if ( !event_target_element ) {
902
+ // for some reason event target is not specificed
903
+ return true;
904
+ }
905
+
906
+ if ( !event_target_element.closest( '[name=update_cart]' ) ) {
907
+ return true;
908
+ }
909
+
910
  gtm4wp_handle_cart_qty_change();
911
  });
912
 
913
+ document.addEventListener( 'keypress', function( e ) {
914
+ let event_target_element = e.target;
915
+
916
+ if ( !event_target_element ) {
917
+ // for some reason event target is not specificed
918
+ return true;
919
+ }
920
+
921
+ if ( !event_target_element.closest( '.woocommerce-cart-form input[type=number]' ) ) {
922
+ return true;
923
+ }
924
+
925
  gtm4wp_handle_cart_qty_change();
926
  });
927
  }
928
 
929
  // codes for enhanced ecommerce events on checkout page
930
+ if ( gtm4wp_is_checkout ) {
931
  window.gtm4wp_checkout_step_offset = window.gtm4wp_checkout_step_offset || 0;
932
  window.gtm4wp_checkout_value = window.gtm4wp_checkout_value || 0;
933
  window.gtm4wp_checkout_products = window.gtm4wp_checkout_products || [];
934
  window.gtm4wp_checkout_products_ga4 = window.gtm4wp_checkout_products_ga4 || [];
935
 
 
 
 
936
  // this checkout step is not reported to GA4 as currently there is no option to report in-between custom steps
937
+ document.addEventListener( 'blur', function( e ) {
938
+ let event_target_element = e.target;
939
+
940
+ if ( !event_target_element ) {
941
+ // for some reason event target is not specificed
942
+ return true;
943
+ }
944
+
945
+ if ( !event_target_element.closest || !event_target_element.closest( 'input[name^=shipping_]:not(input[name^=shipping_method])' ) ) {
946
+ return true;
947
+ }
948
+
949
  // do not report checkout step if already reported
950
  if ( gtm4wp_checkout_step_fired.indexOf( 'shipping' ) > -1 ) {
951
  return;
952
  }
953
 
954
  // do not report checkout step if user is traversing through the section without filling in any data
955
+ if ( event_target_element.value.trim() == '' ) {
956
  return;
957
  }
958
 
972
  gtm4wp_checkout_step_fired.push( 'shipping' );
973
  });
974
 
975
+ document.addEventListener( 'change', function( e ) {
976
+ let event_target_element = e.target;
 
 
 
977
 
978
+ if ( !event_target_element ) {
979
+ // for some reason event target is not specificed
980
+ return true;
981
  }
982
 
983
+ if ( !event_target_element.closest( 'input[name^=shipping_method]' ) ) {
984
+ return true;
 
 
 
 
 
985
  }
986
 
987
+ gtm4wp_handle_shipping_method_change();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
988
  });
989
 
990
+ document.addEventListener( 'change', function( e ) {
991
+ let event_target_element = e.target;
 
 
 
992
 
993
+ if ( !event_target_element ) {
994
+ // for some reason event target is not specificed
995
+ return true;
996
  }
997
 
998
+ if ( !event_target_element.closest( 'input[name=payment_method]' ) ) {
999
+ return true;
 
 
 
 
 
1000
  }
1001
 
1002
+ gtm4wp_handle_payment_method_change();
1003
+ });
 
 
 
 
 
 
 
 
 
 
 
1004
 
1005
+ document.addEventListener( 'submit', function( e ) {
1006
+ let event_target_element = e.target;
 
 
 
 
 
 
 
 
1007
 
1008
+ if ( !event_target_element ) {
1009
+ // for some reason event target is not specificed
1010
+ return true;
1011
+ }
1012
+
1013
+ if ( !event_target_element.closest( 'form[name=checkout]' ) ) {
1014
+ return true;
1015
+ }
1016
 
 
1017
  if ( gtm4wp_checkout_step_fired.indexOf( 'shipping_method' ) == -1 ) {
1018
  // shipping methods are not visible if only one is available
1019
  // and if the user has already a pre-selected method, no click event will fire to report the checkout step
1020
+ gtm4wp_handle_shipping_method_change();
 
 
 
 
 
 
1021
  }
1022
 
1023
  if ( gtm4wp_checkout_step_fired.indexOf( 'payment_method' ) == -1 ) {
1024
  // if the user has already a pre-selected method, no click event will fire to report the checkout step
1025
+ gtm4wp_handle_payment_method_change();
1026
  }
1027
 
1028
+ let shipping_el = document.querySelector( 'input[name^=shipping_method]:checked' );
1029
+ if ( !shipping_el ) {
1030
+ shipping_el = document.querySelector( 'input[name^=shipping_method]' ); // select the first input element
1031
  }
1032
+ if ( shipping_el ) {
1033
  window[ gtm4wp_datalayer_name ].push({
1034
  'event': 'gtm4wp.checkoutOptionEEC',
1035
  'ecommerce': {
1036
  'checkout_option': {
1037
  'actionField': {
1038
  'step': 3 + window.gtm4wp_checkout_step_offset + gtm4wp_shipping_payment_method_step_offset,
1039
+ 'option': 'Shipping: ' + shipping_el.value
1040
  }
1041
  }
1042
  }
1043
  });
1044
  }
1045
 
1046
+ let payment_el = document.querySelector( '.payment_methods input:checked' );
1047
+ if ( !payment_el ) {
1048
+ payment_el = document.querySelector( 'input[name^=payment_method]' ); // select the first input element
1049
  }
1050
+ if ( payment_el ) {
1051
  window[ gtm4wp_datalayer_name ].push({
1052
  'event': 'gtm4wp.checkoutOptionEEC',
1053
  'ecommerce': {
1054
  'checkout_option': {
1055
  'actionField': {
1056
  'step': 4 + window.gtm4wp_checkout_step_offset + gtm4wp_shipping_payment_method_step_offset,
1057
+ 'option': 'Payment: ' + payment_el.value
1058
  }
1059
  }
1060
  }
1064
  }
1065
 
1066
  // codes for Google Ads dynamic remarketing
1067
+ // this part of the code is deprecated and will be removed in a later version
1068
+ // therefore jQuery usage will be not rewritten
1069
+ // turn of the deprecated Google Ads remarketing feature and this code will not execute
1070
+ if ( window.gtm4wp_remarketing&& !gtm4wp_is_cart && !gtm4wp_is_checkout ) {
1071
  if ( jQuery( '.gtm4wp_productdata' ).length > 0 ) {
1072
  for( var i=0; i<window[ gtm4wp_datalayer_name ].length; i++ ) {
1073
  if ( window[ gtm4wp_datalayer_name ][ i ][ 'ecomm_prodid' ] ) {
1101
  'event': 'view_item',
1102
  'ecommerce': {
1103
  'currency': gtm4wp_currency,
1104
+ 'value': item.ecommerce.detail.products[0].price,
1105
  'items': [ gtm4wp_map_eec_to_ga4( item.ecommerce.detail.products[0] ) ]
1106
  }
1107
  });
1108
  }
1109
 
1110
+ if ( item && item.ecommerce && ( item.ecommerce.cart || (item.ecommerce.checkout && gtm4wp_is_cart) ) ) {
1111
+ let source_products = item.ecommerce.cart || item.ecommerce.checkout.products;
1112
+ let ga4_products = [];
1113
+ let sum_value = 0;
1114
 
1115
  source_products.forEach(function( product ) {
1116
  ga4_products.push( gtm4wp_map_eec_to_ga4( product ) );
1127
  });
1128
  }
1129
 
1130
+ if ( item && item.ecommerce && item.ecommerce.checkout && !gtm4wp_is_cart ) {
1131
+ let ga4_products = [];
1132
+ let sum_value = 0;
1133
 
1134
  item.ecommerce.checkout.products.forEach(function( product ) {
1135
  ga4_products.push( gtm4wp_map_eec_to_ga4( product ) );
1148
 
1149
  // present if product is readded into cart just after removel
1150
  if ( item && item.ecommerce && item.ecommerce.add ) {
1151
+ let ga4_products = [];
1152
+ let sum_value = 0;
1153
 
1154
  item.ecommerce.add.products.forEach(function( product ) {
1155
  ga4_products.push( gtm4wp_map_eec_to_ga4( product ) );
1167
  }
1168
 
1169
  if ( item && item.ecommerce && item.ecommerce.purchase ) {
1170
+ let ga4_products = [];
1171
  item.ecommerce.purchase.products.forEach(function( product ) {
1172
  ga4_products.push( gtm4wp_map_eec_to_ga4( product ) );
1173
  });
js/gtm4wp-youtube.js CHANGED
@@ -1,221 +1,226 @@
1
- var gtm4wp_youtube_percentage_tracking = 10;
2
- var gtm4wp_youtube_percentage_tracking_timeouts = {};
3
- var gtm4wp_youtube_percentage_tracking_marks = {};
4
-
5
- if ( typeof onYouTubeIframeAPIReady === "undefined" ) {
6
- window.onYouTubeIframeAPIReady = function() {
7
- window[ gtm4wp_datalayer_name ].push({
8
- 'event': 'gtm4wp.mediaApiReady',
9
- 'mediaType': 'youtube'
10
- });
11
-
12
- jQuery( "iframe[src^='https://www.youtube.com/embed']" ).each( function() {
13
- var gtm4wp_jqthis = jQuery( this );
14
- var playerID = gtm4wp_jqthis.attr( "id" );
15
-
16
- if ( ( playerID === undefined ) || ( playerID === "" ) ) {
17
- var _gtm4wp_temp = gtm4wp_jqthis.attr( "src" ).split( "?" );
18
- var _gtm4wp_temp2 = _gtm4wp_temp[ 0 ].split( "/" );
19
-
20
- playerID = "youtubeplayer_" + _gtm4wp_temp2[ _gtm4wp_temp2.length-1 ];
21
- gtm4wp_jqthis.attr( "id", playerID );
22
- }
23
-
24
- var gtm4wp_yturl = gtm4wp_jqthis.attr( "src" );
25
- if ( gtm4wp_yturl.indexOf( "enablejsapi=1" ) == -1 ) {
26
- if ( gtm4wp_yturl.indexOf( "?" ) == -1 ) {
27
- gtm4wp_yturl += "?";
28
- }
29
-
30
- gtm4wp_yturl += "&enablejsapi=1&origin=" + document.location.protocol + "//" + document.location.hostname;
31
-
32
- gtm4wp_jqthis.attr( "src", gtm4wp_yturl );
33
- }
34
-
35
- player = new YT.Player( playerID, {
36
- events: {
37
- 'onReady': gtm4wp_onYouTubePlayerReady,
38
- 'onStateChange': gtm4wp_onYouTubePlayerStateChange,
39
- 'onPlaybackQualityChange': gtm4wp_onYouTubePlaybackQualityChange,
40
- 'onPlaybackRateChange': gtm4wp_onYouTubePlaybackRateChange,
41
- 'onError': gtm4wp_onYouTubeError,
42
- 'onApiChange': gtm4wp_onYouTubeApiChange
43
- }
44
- });
45
- });
46
- };
47
-
48
- var tag = document.createElement( 'script' );
49
- tag.src = "//www.youtube.com/iframe_api";
50
- var firstScriptTag = document.getElementsByTagName( 'script' )[0];
51
- firstScriptTag.parentNode.insertBefore( tag, firstScriptTag );
52
- } else {
53
- var gtm4wp_err = new Error( "Another code is already utilizing YouTube API, GTM4WP plugin can not load YouTube tracking!" );
54
- throw gtm4wp_err;
55
- }
56
-
57
- function gtm4wp_onYouTubePlayerReady( event ) {
58
- var videodata = event.target.getVideoData();
59
-
60
- window[ gtm4wp_datalayer_name ].push({
61
- 'event': 'gtm4wp.mediaPlayerReady',
62
- 'mediaType': 'youtube',
63
- 'mediaData': {
64
- 'id': videodata.video_id,
65
- 'author': videodata.author,
66
- 'title': videodata.title,
67
- 'url': event.target.getVideoUrl(),
68
- 'duration': event.target.getDuration()
69
- },
70
- 'mediaCurrentTime': event.target.getCurrentTime()
71
- });
72
- }
73
-
74
- function gtm4wp_onYouTubePlayerStateChange( event ) {
75
- var playerState = "unknown";
76
- switch( event.data ) {
77
- case -1: playerState = "unstarted"; break;
78
- case YT.PlayerState.ENDED: playerState = "ended"; break;
79
- case YT.PlayerState.PLAYING: playerState = "play"; break;
80
- case YT.PlayerState.PAUSED: playerState = "pause"; break;
81
- case YT.PlayerState.BUFFERING: playerState = "buffering"; break;
82
- case YT.PlayerState.CUED: playerState = "cued"; break;
83
- }
84
-
85
- var videoId = event.target.getVideoData().video_id;
86
-
87
- if ( ( YT.PlayerState.PLAYING == event.data ) && ( gtm4wp_youtube_percentage_tracking > 0 ) ) {
88
- gtm4wp_youtube_percentage_tracking_timeouts[ videoId ] = setInterval(function() {
89
- gtm4wp_onYouTubePercentageChange( event );
90
- }, 1000);
91
- } else {
92
- if ( gtm4wp_youtube_percentage_tracking_timeouts[ videoId ] ) {
93
- clearInterval( gtm4wp_youtube_percentage_tracking_timeouts[ videoId ] );
94
- }
95
- }
96
-
97
- var videodata = event.target.getVideoData();
98
-
99
- window[ gtm4wp_datalayer_name ].push({
100
- 'event': 'gtm4wp.mediaPlayerStateChange',
101
- 'mediaType': 'youtube',
102
- 'mediaData': {
103
- 'id': videodata.video_id,
104
- 'author': videodata.author,
105
- 'title': videodata.title,
106
- 'url': event.target.getVideoUrl(),
107
- 'duration': event.target.getDuration()
108
- },
109
- 'mediaPlayerState': playerState,
110
- 'mediaCurrentTime': event.target.getCurrentTime()
111
- });
112
- }
113
-
114
- function gtm4wp_onYouTubePlaybackQualityChange( event ) {
115
- var videodata = event.target.getVideoData();
116
-
117
- window[ gtm4wp_datalayer_name ].push({
118
- 'event': 'gtm4wp.mediaPlayerEvent',
119
- 'mediaType': 'youtube',
120
- 'mediaData': {
121
- 'id': videodata.video_id,
122
- 'author': videodata.author,
123
- 'title': videodata.title,
124
- 'url': event.target.getVideoUrl(),
125
- 'duration': event.target.getDuration()
126
- },
127
- 'mediaCurrentTime': event.target.getCurrentTime(),
128
- 'mediaPlayerEvent': 'quality-change',
129
- 'mediaPlayerEventParam': event.data
130
- });
131
- }
132
-
133
- function gtm4wp_onYouTubePlaybackRateChange( event ) {
134
- var videodata = event.target.getVideoData();
135
-
136
- window[ gtm4wp_datalayer_name ].push({
137
- 'event': 'gtm4wp.mediaPlayerEvent',
138
- 'mediaType': 'youtube',
139
- 'mediaData': {
140
- 'id': videodata.video_id,
141
- 'author': videodata.author,
142
- 'title': videodata.title,
143
- 'url': event.target.getVideoUrl(),
144
- 'duration': event.target.getDuration()
145
- },
146
- 'mediaCurrentTime': event.target.getCurrentTime(),
147
- 'mediaPlayerEvent': 'ratechange',
148
- 'mediaPlayerEventParam': event.data
149
- });
150
- }
151
-
152
- function gtm4wp_onYouTubeError( event ) {
153
- var videodata = event.target.getVideoData();
154
-
155
- window[ gtm4wp_datalayer_name ].push({
156
- 'event': 'gtm4wp.mediaPlayerEvent',
157
- 'mediaType': 'youtube',
158
- 'mediaData': {
159
- 'id': videodata.video_id,
160
- 'author': videodata.author,
161
- 'title': videodata.title,
162
- 'url': event.target.getVideoUrl(),
163
- 'duration': event.target.getDuration()
164
- },
165
- 'mediaCurrentTime': event.target.getCurrentTime(),
166
- 'mediaPlayerEvent': 'error',
167
- 'mediaPlayerEventParam': event.data
168
- });
169
- }
170
-
171
- function gtm4wp_onYouTubeApiChange( event ) {
172
- var videodata = event.target.getVideoData();
173
-
174
- window[ gtm4wp_datalayer_name ].push({
175
- 'event': 'gtm4wp.mediaPlayerEvent',
176
- 'mediaType': 'youtube',
177
- 'mediaData': {
178
- 'id': videodata.video_id,
179
- 'author': videodata.author,
180
- 'title': videodata.title,
181
- 'url': event.target.getVideoUrl(),
182
- 'duration': event.target.getDuration()
183
- },
184
- 'mediaCurrentTime': event.target.getCurrentTime(),
185
- 'mediaPlayerEvent': 'api-change',
186
- 'mediaPlayerEventParam': event.data
187
- });
188
- }
189
-
190
- function gtm4wp_onYouTubePercentageChange( event ) {
191
- var videoId = event.target.getVideoData().video_id;
192
- var videoCurrentTime = event.target.getCurrentTime();
193
- var videoDuration = event.target.getDuration();
194
- var videoPercentage = Math.floor( videoCurrentTime / videoDuration * 100 );
195
-
196
- if ( typeof gtm4wp_youtube_percentage_tracking_marks[ videoId ] == "undefined" ) {
197
- gtm4wp_youtube_percentage_tracking_marks[ videoId ] = [];
198
- }
199
-
200
- var videodata = event.target.getVideoData();
201
-
202
- for( var i=0; i<100; i+=gtm4wp_youtube_percentage_tracking ) {
203
- if ( ( videoPercentage > i ) && ( gtm4wp_youtube_percentage_tracking_marks[ videoId ].indexOf( i ) == -1 ) ) {
204
- gtm4wp_youtube_percentage_tracking_marks[ videoId ].push( i );
205
-
206
- window[ gtm4wp_datalayer_name ].push({
207
- 'event': 'gtm4wp.mediaPlaybackPercentage',
208
- 'mediaType': 'youtube',
209
- 'mediaData': {
210
- 'id': videodata.video_id,
211
- 'author': videodata.author,
212
- 'title': videodata.title,
213
- 'url': event.target.getVideoUrl(),
214
- 'duration': event.target.getDuration()
215
- },
216
- 'mediaCurrentTime': event.target.getCurrentTime(),
217
- 'mediaPercentage': i
218
- });
219
- }
220
- }
221
- }
 
 
 
 
 
1
+ let gtm4wp_youtube_percentage_tracking = 10;
2
+ let gtm4wp_youtube_percentage_tracking_timeouts = {};
3
+ let gtm4wp_youtube_percentage_tracking_marks = {};
4
+
5
+ if ( typeof onYouTubeIframeAPIReady === "undefined" ) {
6
+ window.onYouTubeIframeAPIReady = function() {
7
+ window[ gtm4wp_datalayer_name ].push({
8
+ 'event': 'gtm4wp.mediaApiReady',
9
+ 'mediaType': 'youtube'
10
+ });
11
+
12
+ const gtm4wp_youtube_frames = document.querySelectorAll( "iframe[src^='https://www.youtube.com/embed']" );
13
+ if ( !gtm4wp_youtube_frames || gtm4wp_youtube_frames.length == 0 ) {
14
+ return;
15
+ }
16
+
17
+ gtm4wp_youtube_frames.forEach( function( youtube_frame ) {
18
+ let playerID = youtube_frame.getAttribute( "id" );
19
+
20
+ if ( ( playerID === null ) || ( playerID === undefined ) || ( playerID === "" ) ) {
21
+ const _gtm4wp_temp = youtube_frame.getAttribute( "src" ).split( "?" );
22
+ const _gtm4wp_temp2 = _gtm4wp_temp[ 0 ].split( "/" );
23
+
24
+ playerID = "youtubeplayer_" + _gtm4wp_temp2[ _gtm4wp_temp2.length-1 ];
25
+ youtube_frame.setAttribute( "id", playerID );
26
+ }
27
+
28
+ let gtm4wp_yturl = youtube_frame.getAttribute( "src" );
29
+ if ( gtm4wp_yturl.indexOf( "enablejsapi=1" ) == -1 ) {
30
+ if ( gtm4wp_yturl.indexOf( "?" ) == -1 ) {
31
+ gtm4wp_yturl += "?";
32
+ }
33
+
34
+ gtm4wp_yturl += "&enablejsapi=1&origin=" + document.location.protocol + "//" + document.location.hostname;
35
+
36
+ youtube_frame.setAttribute( "src", gtm4wp_yturl );
37
+ }
38
+
39
+ player = new YT.Player( playerID, {
40
+ events: {
41
+ 'onReady': gtm4wp_onYouTubePlayerReady,
42
+ 'onStateChange': gtm4wp_onYouTubePlayerStateChange,
43
+ 'onPlaybackQualityChange': gtm4wp_onYouTubePlaybackQualityChange,
44
+ 'onPlaybackRateChange': gtm4wp_onYouTubePlaybackRateChange,
45
+ 'onError': gtm4wp_onYouTubeError,
46
+ 'onApiChange': gtm4wp_onYouTubeApiChange
47
+ }
48
+ });
49
+ });
50
+ };
51
+
52
+ let tag = document.createElement( 'script' );
53
+ tag.src = "//www.youtube.com/iframe_api";
54
+ let firstScriptTag = document.getElementsByTagName( 'script' )[0];
55
+ firstScriptTag.parentNode.insertBefore( tag, firstScriptTag );
56
+ } else {
57
+ let gtm4wp_err = new Error( "Another code is already utilizing YouTube API, GTM4WP plugin can not load YouTube tracking!" );
58
+ throw gtm4wp_err;
59
+ }
60
+
61
+ function gtm4wp_onYouTubePlayerReady( event ) {
62
+ const videodata = event.target.getVideoData();
63
+
64
+ window[ gtm4wp_datalayer_name ].push({
65
+ 'event': 'gtm4wp.mediaPlayerReady',
66
+ 'mediaType': 'youtube',
67
+ 'mediaData': {
68
+ 'id': videodata.video_id,
69
+ 'author': videodata.author,
70
+ 'title': videodata.title,
71
+ 'url': event.target.getVideoUrl(),
72
+ 'duration': event.target.getDuration()
73
+ },
74
+ 'mediaCurrentTime': event.target.getCurrentTime()
75
+ });
76
+ }
77
+
78
+ function gtm4wp_onYouTubePlayerStateChange( event ) {
79
+ let playerState = "unknown";
80
+
81
+ switch( event.data ) {
82
+ case -1: playerState = "unstarted"; break;
83
+ case YT.PlayerState.ENDED: playerState = "ended"; break;
84
+ case YT.PlayerState.PLAYING: playerState = "play"; break;
85
+ case YT.PlayerState.PAUSED: playerState = "pause"; break;
86
+ case YT.PlayerState.BUFFERING: playerState = "buffering"; break;
87
+ case YT.PlayerState.CUED: playerState = "cued"; break;
88
+ }
89
+
90
+ const videoId = event.target.getVideoData().video_id;
91
+
92
+ if ( ( YT.PlayerState.PLAYING == event.data ) && ( gtm4wp_youtube_percentage_tracking > 0 ) ) {
93
+ gtm4wp_youtube_percentage_tracking_timeouts[ videoId ] = setInterval(function() {
94
+ gtm4wp_onYouTubePercentageChange( event );
95
+ }, 1000);
96
+ } else {
97
+ if ( gtm4wp_youtube_percentage_tracking_timeouts[ videoId ] ) {
98
+ clearInterval( gtm4wp_youtube_percentage_tracking_timeouts[ videoId ] );
99
+ }
100
+ }
101
+
102
+ const videodata = event.target.getVideoData();
103
+
104
+ window[ gtm4wp_datalayer_name ].push({
105
+ 'event': 'gtm4wp.mediaPlayerStateChange',
106
+ 'mediaType': 'youtube',
107
+ 'mediaData': {
108
+ 'id': videodata.video_id,
109
+ 'author': videodata.author,
110
+ 'title': videodata.title,
111
+ 'url': event.target.getVideoUrl(),
112
+ 'duration': event.target.getDuration()
113
+ },
114
+ 'mediaPlayerState': playerState,
115
+ 'mediaCurrentTime': event.target.getCurrentTime()
116
+ });
117
+ }
118
+
119
+ function gtm4wp_onYouTubePlaybackQualityChange( event ) {
120
+ const videodata = event.target.getVideoData();
121
+
122
+ window[ gtm4wp_datalayer_name ].push({
123
+ 'event': 'gtm4wp.mediaPlayerEvent',
124
+ 'mediaType': 'youtube',
125
+ 'mediaData': {
126
+ 'id': videodata.video_id,
127
+ 'author': videodata.author,
128
+ 'title': videodata.title,
129
+ 'url': event.target.getVideoUrl(),
130
+ 'duration': event.target.getDuration()
131
+ },
132
+ 'mediaCurrentTime': event.target.getCurrentTime(),
133
+ 'mediaPlayerEvent': 'quality-change',
134
+ 'mediaPlayerEventParam': event.data
135
+ });
136
+ }
137
+
138
+ function gtm4wp_onYouTubePlaybackRateChange( event ) {
139
+ const videodata = event.target.getVideoData();
140
+
141
+ window[ gtm4wp_datalayer_name ].push({
142
+ 'event': 'gtm4wp.mediaPlayerEvent',
143
+ 'mediaType': 'youtube',
144
+ 'mediaData': {
145
+ 'id': videodata.video_id,
146
+ 'author': videodata.author,
147
+ 'title': videodata.title,
148
+ 'url': event.target.getVideoUrl(),
149
+ 'duration': event.target.getDuration()
150
+ },
151
+ 'mediaCurrentTime': event.target.getCurrentTime(),
152
+ 'mediaPlayerEvent': 'ratechange',
153
+ 'mediaPlayerEventParam': event.data
154
+ });
155
+ }
156
+
157
+ function gtm4wp_onYouTubeError( event ) {
158
+ const videodata = event.target.getVideoData();
159
+
160
+ window[ gtm4wp_datalayer_name ].push({
161
+ 'event': 'gtm4wp.mediaPlayerEvent',
162
+ 'mediaType': 'youtube',
163
+ 'mediaData': {
164
+ 'id': videodata.video_id,
165
+ 'author': videodata.author,
166
+ 'title': videodata.title,
167
+ 'url': event.target.getVideoUrl(),
168
+ 'duration': event.target.getDuration()
169
+ },
170
+ 'mediaCurrentTime': event.target.getCurrentTime(),
171
+ 'mediaPlayerEvent': 'error',
172
+ 'mediaPlayerEventParam': event.data
173
+ });
174
+ }
175
+
176
+ function gtm4wp_onYouTubeApiChange( event ) {
177
+ const videodata = event.target.getVideoData();
178
+
179
+ window[ gtm4wp_datalayer_name ].push({
180
+ 'event': 'gtm4wp.mediaPlayerEvent',
181
+ 'mediaType': 'youtube',
182
+ 'mediaData': {
183
+ 'id': videodata.video_id,
184
+ 'author': videodata.author,
185
+ 'title': videodata.title,
186
+ 'url': event.target.getVideoUrl(),
187
+ 'duration': event.target.getDuration()
188
+ },
189
+ 'mediaCurrentTime': event.target.getCurrentTime(),
190
+ 'mediaPlayerEvent': 'api-change',
191
+ 'mediaPlayerEventParam': event.data
192
+ });
193
+ }
194
+
195
+ function gtm4wp_onYouTubePercentageChange( event ) {
196
+ const videoId = event.target.getVideoData().video_id;
197
+ const videoCurrentTime = event.target.getCurrentTime();
198
+ const videoDuration = event.target.getDuration();
199
+ const videoPercentage = Math.floor( videoCurrentTime / videoDuration * 100 );
200
+
201
+ if ( typeof gtm4wp_youtube_percentage_tracking_marks[ videoId ] == "undefined" ) {
202
+ gtm4wp_youtube_percentage_tracking_marks[ videoId ] = [];
203
+ }
204
+
205
+ const videodata = event.target.getVideoData();
206
+
207
+ for( let i=0; i<100; i+=gtm4wp_youtube_percentage_tracking ) {
208
+ if ( ( videoPercentage > i ) && ( gtm4wp_youtube_percentage_tracking_marks[ videoId ].indexOf( i ) == -1 ) ) {
209
+ gtm4wp_youtube_percentage_tracking_marks[ videoId ].push( i );
210
+
211
+ window[ gtm4wp_datalayer_name ].push({
212
+ 'event': 'gtm4wp.mediaPlaybackPercentage',
213
+ 'mediaType': 'youtube',
214
+ 'mediaData': {
215
+ 'id': videodata.video_id,
216
+ 'author': videodata.author,
217
+ 'title': videodata.title,
218
+ 'url': event.target.getVideoUrl(),
219
+ 'duration': event.target.getDuration()
220
+ },
221
+ 'mediaCurrentTime': event.target.getCurrentTime(),
222
+ 'mediaPercentage': i
223
+ });
224
+ }
225
+ }
226
+ }
public/frontend.php CHANGED
@@ -1,915 +1,990 @@
1
- <?php
2
- define( 'GTM4WP_WPFILTER_COMPILE_DATALAYER', 'gtm4wp_compile_datalayer' );
3
- define( 'GTM4WP_WPFILTER_COMPILE_REMARKTING', 'gtm4wp_compile_remarkering' );
4
- define( 'GTM4WP_WPFILTER_AFTER_DATALAYER', 'gtm4wp_after_datalayer' );
5
- define( 'GTM4WP_WPFILTER_GETTHEGTMTAG', 'gtm4wp_get_the_gtm_tag' );
6
- define( 'GTM4WP_WPACTION_ADDGLOBALVARS', 'gtm4wp_add_global_vars' );
7
-
8
- $GLOBALS['gtm4wp_container_code_written'] = false;
9
-
10
- // check for empty is needed to prevent error in WP CLI
11
- // bugfix by Patrick Holberg Hesselberg
12
- if ( empty( $GLOBALS['gtm4wp_options'] ) || ( $GLOBALS['gtm4wp_options'][ GTM4WP_OPTION_DATALAYER_NAME ] == '' ) ) {
13
- $GLOBALS['gtm4wp_datalayer_name'] = 'dataLayer';
14
- } else {
15
- $GLOBALS['gtm4wp_datalayer_name'] = $GLOBALS['gtm4wp_options'][ GTM4WP_OPTION_DATALAYER_NAME ];
16
- }
17
-
18
- // Setting Global Variable to Store JSON based Datalayer for Intergrations
19
- $GLOBALS['gtm4wp_datalayer_json'] = '';
20
- $GLOBALS['gtm4wp_datalayer_globalvars'] = '';
21
-
22
- // Moving include to top due to hierarchy of includes
23
- if ( isset( $GLOBALS['gtm4wp_options'] ) && ( '' != $GLOBALS['gtm4wp_options'][ GTM4WP_OPTION_INTEGRATE_AMPID ] ) ) {
24
- require_once dirname( __FILE__ ) . '/../integration/amp.php';
25
- }
26
- if ( ! function_exists( 'gtm4wp_amp_running' ) ) {
27
- function gtm4wp_amp_running() {
28
- return false;
29
- }
30
- }
31
-
32
- /**
33
- * Converts bool false to string false for JS
34
- *
35
- * @author Vincent Koc <https://github.com/koconder/>
36
- * @return mixed Returs object or string false
37
- */
38
- function gtm4wp_escjs_boolean( $obj ) {
39
- if ( empty( $obj ) || is_null( $obj ) || ! $obj ) {
40
- return 'false';
41
- } else {
42
- return $obj;
43
- }
44
- }
45
-
46
- /**
47
- * Original copyright:
48
- * By Grant Burton @ BURTONTECH.COM
49
- *
50
- * Code improved by Thomas Geiger
51
- */
52
- function gtm4wp_get_user_ip() {
53
- if ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
54
- foreach ( explode( ',', $_SERVER['HTTP_X_FORWARDED_FOR'] ) as $ip ) {
55
- if ( filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) !== false ) {
56
- return $ip;
57
- }
58
- }
59
- }
60
-
61
- $possible_ip_variables = array(
62
- 'HTTP_CLIENT_IP',
63
- 'HTTP_X_FORWARDED',
64
- 'HTTP_X_CLUSTER_CLIENT_IP',
65
- 'HTTP_FORWARDED_FOR',
66
- 'HTTP_FORWARDED',
67
- 'REMOTE_ADDR'
68
- );
69
-
70
- foreach( $possible_ip_variables as $one_ip_variable ) {
71
- if (
72
- ! empty( $_SERVER[ $one_ip_variable ] )
73
- && ( filter_var( $_SERVER[ $one_ip_variable ], FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) !== false )
74
- ) {
75
- return $_SERVER[ $one_ip_variable ];
76
- }
77
- }
78
-
79
- return '';
80
- }
81
-
82
- if ( ! function_exists( 'getallheaders' ) ) {
83
- function getallheaders() {
84
- $headers = array();
85
- foreach ( $_SERVER as $name => $value ) {
86
- if ( substr( $name, 0, 5 ) == 'HTTP_' ) {
87
- $headers[ str_replace( ' ', '-', ucwords( strtolower( str_replace( '_', ' ', substr( $name, 5 ) ) ) ) ) ] = $value;
88
- }
89
- }
90
-
91
- return $headers;
92
- }
93
- }
94
-
95
- function gtm4wp_add_basic_datalayer_data( $dataLayer ) {
96
- global $wp_query, $gtm4wp_options, $gtm4wp_entity_ids;
97
-
98
- if ( $gtm4wp_options[ GTM4WP_OPTION_DONOTTRACK ] ) {
99
- if ( ! empty( $_SERVER['HTTP_DNT'] ) ) {
100
- $dataLayer['visitorDoNotTrack'] = (int) ( $_SERVER['HTTP_DNT'] );
101
- } else {
102
- $dataLayer['visitorDoNotTrack'] = 0;
103
- }
104
- }
105
-
106
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_SITEID ] || $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_SITENAME ] ) {
107
- $dataLayer['siteID'] = 0;
108
- $dataLayer['siteName'] = '';
109
-
110
- if ( function_exists( 'get_blog_details' ) ) {
111
- $gtm4wp_blogdetails = get_blog_details();
112
-
113
- $dataLayer['siteID'] = $gtm4wp_blogdetails->blog_id;
114
- $dataLayer['siteName'] = $gtm4wp_blogdetails->blogname;
115
- }
116
- }
117
-
118
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_LOGGEDIN ] ) {
119
- if ( is_user_logged_in() ) {
120
- $dataLayer['visitorLoginState'] = 'logged-in';
121
- } else {
122
- $dataLayer['visitorLoginState'] = 'logged-out';
123
- }
124
- }
125
-
126
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_USERROLE ] || $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_USEREMAIL ] || $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_USERREGDATE ] ) {
127
- $current_user = wp_get_current_user();
128
-
129
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_USERROLE ] ) {
130
- $dataLayer['visitorType'] = ( empty( $current_user->roles[0] ) ? 'visitor-logged-out' : $current_user->roles[0] );
131
- }
132
-
133
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_USEREMAIL ] ) {
134
- $dataLayer['visitorEmail'] = ( empty( $current_user->user_email ) ? '' : $current_user->user_email );
135
- }
136
-
137
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_USERREGDATE ] ) {
138
- $dataLayer['visitorRegistrationDate'] = ( empty( $current_user->user_registered ) ? '' : strtotime( $current_user->user_registered ) );
139
- }
140
-
141
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_USERNAME ] ) {
142
- $dataLayer['visitorUsername'] = ( empty( $current_user->user_login ) ? '' : $current_user->user_login );
143
- }
144
- }
145
-
146
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_USERID ] ) {
147
- $_gtm4wp_userid = get_current_user_id();
148
- if ( $_gtm4wp_userid > 0 ) {
149
- $dataLayer['visitorId'] = $_gtm4wp_userid;
150
- }
151
- }
152
-
153
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_VISITOR_IP ] ) {
154
- $dataLayer['visitorIP'] = esc_js( gtm4wp_get_user_ip() );
155
- }
156
-
157
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTTITLE ] ) {
158
- $dataLayer['pageTitle'] = strip_tags( wp_title( '|', false, 'right' ) );
159
- }
160
-
161
- if ( is_singular() ) {
162
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTTYPE ] ) {
163
- $dataLayer['pagePostType'] = get_post_type();
164
- $dataLayer['pagePostType2'] = 'single-' . get_post_type();
165
- }
166
-
167
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_CATEGORIES ] ) {
168
- $_post_cats = get_the_category();
169
- if ( $_post_cats ) {
170
- $dataLayer['pageCategory'] = array();
171
- foreach ( $_post_cats as $_one_cat ) {
172
- $dataLayer['pageCategory'][] = $_one_cat->slug;
173
- }
174
- }
175
- }
176
-
177
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_TAGS ] ) {
178
- $_post_tags = get_the_tags();
179
- if ( $_post_tags ) {
180
- $dataLayer['pageAttributes'] = array();
181
- foreach ( $_post_tags as $_one_tag ) {
182
- $dataLayer['pageAttributes'][] = $_one_tag->slug;
183
- }
184
- }
185
- }
186
-
187
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_AUTHORID ] || $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_AUTHOR ] ) {
188
- $postuser = get_userdata( $GLOBALS['post']->post_author );
189
-
190
- if ( false !== $postuser ) {
191
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_AUTHORID ] ) {
192
- $dataLayer['pagePostAuthorID'] = $postuser->ID;
193
- }
194
-
195
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_AUTHOR ] ) {
196
- $dataLayer['pagePostAuthor'] = $postuser->display_name;
197
- }
198
- }
199
- }
200
-
201
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTDATE ] ) {
202
- $dataLayer['pagePostDate'] = get_the_date();
203
- $dataLayer['pagePostDateYear'] = get_the_date( 'Y' );
204
- $dataLayer['pagePostDateMonth'] = get_the_date( 'm' );
205
- $dataLayer['pagePostDateDay'] = get_the_date( 'd' );
206
- }
207
-
208
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTTERMLIST ] ) {
209
- $dataLayer["pagePostTerms"] = array();
210
- $object_taxonomies = get_object_taxonomies( get_post_type() );
211
- foreach( $object_taxonomies as $one_object_taxonomy ) {
212
- $post_taxonomy_values = get_the_terms( $GLOBALS[ "post" ]->ID, $one_object_taxonomy );
213
- if ( is_array( $post_taxonomy_values ) ) {
214
- $dataLayer["pagePostTerms"][$one_object_taxonomy] = array();
215
- foreach( $post_taxonomy_values as $one_taxonomy_value ) {
216
- $dataLayer["pagePostTerms"][$one_object_taxonomy][] = $one_taxonomy_value->name;
217
- }
218
- }
219
- }
220
- }
221
- }
222
-
223
- if ( is_archive() || is_post_type_archive() ) {
224
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTTYPE ] ) {
225
- $dataLayer['pagePostType'] = get_post_type();
226
-
227
- if ( is_category() ) {
228
- $dataLayer['pagePostType2'] = 'category-' . get_post_type();
229
- } elseif ( is_tag() ) {
230
- $dataLayer['pagePostType2'] = 'tag-' . get_post_type();
231
- } elseif ( is_tax() ) {
232
- $dataLayer['pagePostType2'] = 'tax-' . get_post_type();
233
- } elseif ( is_author() ) {
234
- $dataLayer['pagePostType2'] = 'author-' . get_post_type();
235
- } elseif ( is_year() ) {
236
- $dataLayer['pagePostType2'] = 'year-' . get_post_type();
237
-
238
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTDATE ] ) {
239
- $dataLayer['pagePostDateYear'] = get_the_date( 'Y' );
240
- }
241
- } elseif ( is_month() ) {
242
- $dataLayer['pagePostType2'] = 'month-' . get_post_type();
243
-
244
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTDATE ] ) {
245
- $dataLayer['pagePostDateYear'] = get_the_date( 'Y' );
246
- $dataLayer['pagePostDateMonth'] = get_the_date( 'm' );
247
- }
248
- } elseif ( is_day() ) {
249
- $dataLayer['pagePostType2'] = 'day-' . get_post_type();
250
-
251
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTDATE ] ) {
252
- $dataLayer['pagePostDate'] = get_the_date();
253
- $dataLayer['pagePostDateYear'] = get_the_date( 'Y' );
254
- $dataLayer['pagePostDateMonth'] = get_the_date( 'm' );
255
- $dataLayer['pagePostDateDay'] = get_the_date( 'd' );
256
- }
257
- } elseif ( is_time() ) {
258
- $dataLayer['pagePostType2'] = 'time-' . get_post_type();
259
- } elseif ( is_date() ) {
260
- $dataLayer['pagePostType2'] = 'date-' . get_post_type();
261
-
262
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTDATE ] ) {
263
- $dataLayer['pagePostDate'] = get_the_date();
264
- $dataLayer['pagePostDateYear'] = get_the_date( 'Y' );
265
- $dataLayer['pagePostDateMonth'] = get_the_date( 'm' );
266
- $dataLayer['pagePostDateDay'] = get_the_date( 'd' );
267
- }
268
- }
269
- }
270
-
271
- if ( ( is_tax() || is_category() ) && $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_CATEGORIES ] ) {
272
- $_post_cats = get_the_category();
273
- $dataLayer['pageCategory'] = array();
274
- foreach ( $_post_cats as $_one_cat ) {
275
- $dataLayer['pageCategory'][] = $_one_cat->slug;
276
- }
277
- }
278
-
279
- if ( ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_AUTHORID ] ) && ( is_author() ) ) {
280
- global $authordata;
281
- $dataLayer['pagePostAuthorID'] = isset( $authordata->ID ) ? $authordata->ID : 0;
282
- }
283
-
284
- if ( ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_AUTHOR ] ) && ( is_author() ) ) {
285
- $dataLayer['pagePostAuthor'] = get_the_author();
286
- }
287
- }
288
-
289
- if ( is_search() ) {
290
- $dataLayer['siteSearchTerm'] = get_search_query();
291
- $dataLayer['siteSearchFrom'] = '';
292
- if ( ! empty( $_SERVER['HTTP_REFERER'] ) ) {
293
- $referer_url_parts = explode( '?', $_SERVER['HTTP_REFERER'] );
294
- if ( count( $referer_url_parts ) > 1 ) {
295
- $dataLayer['siteSearchFrom'] = $referer_url_parts[0] . '?' . rawurlencode( $referer_url_parts[1] );
296
- } else {
297
- $dataLayer['siteSearchFrom'] = $referer_url_parts[0];
298
- }
299
- }
300
- $dataLayer['siteSearchResults'] = $wp_query->post_count;
301
- }
302
-
303
- if ( is_front_page() && $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTTYPE ] ) {
304
- $dataLayer['pagePostType'] = 'frontpage';
305
- }
306
-
307
- if ( ! is_front_page() && is_home() && $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTTYPE ] ) {
308
- $dataLayer['pagePostType'] = 'bloghome';
309
- }
310
-
311
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_BROWSERDATA ] || $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_OSDATA ] || $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_DEVICEDATA ] ) {
312
- spl_autoload_register(
313
- function( $class ) {
314
- $class_parts = explode( '\\', $class );
315
- if ( 'WhichBrowser' == $class_parts[0] ) {
316
- include dirname( __FILE__ ) . '/../integration/whichbrowser/' . str_replace( array( 'WhichBrowser', '\\' ), array( 'src', '/' ), $class ) . '.php';
317
- }
318
- }
319
- );
320
-
321
- require_once dirname( __FILE__ ) . '/../integration/whichbrowser/src/Parser.php';
322
-
323
- $gtp4wp_headers = getallheaders();
324
- if ( ( false === $gtp4wp_headers ) && isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
325
- $gtp4wp_headers = $_SERVER['HTTP_USER_AGENT'];
326
- }
327
- if ( false !== $gtp4wp_headers ) {
328
- $detected = new WhichBrowser\Parser( $gtp4wp_headers );
329
-
330
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_BROWSERDATA ] ) {
331
- $dataLayer['browserName'] = isset( $detected->browser->name ) ? $detected->browser->name : '';
332
- $dataLayer['browserVersion'] = isset( $detected->browser->version->value ) ? $detected->browser->version->value : '';
333
-
334
- $dataLayer['browserEngineName'] = isset( $detected->engine->name ) ? $detected->engine->name : '';
335
- $dataLayer['browserEngineVersion'] = isset( $detected->engine->version->value ) ? $detected->engine->version->value : '';
336
- }
337
-
338
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_OSDATA ] ) {
339
- $dataLayer['osName'] = isset( $detected->os->name ) ? $detected->os->name : '';
340
- $dataLayer['osVersion'] = isset( $detected->os->version->value ) ? $detected->os->version->value : '';
341
- }
342
-
343
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_DEVICEDATA ] ) {
344
- $dataLayer['deviceType'] = isset( $detected->device->type ) ? $detected->device->type : '';
345
- $dataLayer['deviceManufacturer'] = isset( $detected->device->manufacturer ) ? $detected->device->manufacturer : '';
346
- $dataLayer['deviceModel'] = isset( $detected->device->model ) ? $detected->device->model : '';
347
- }
348
- }
349
- }
350
-
351
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTCOUNT ] ) {
352
- $dataLayer['postCountOnPage'] = (int) $wp_query->post_count;
353
- $dataLayer['postCountTotal'] = (int) $wp_query->found_posts;
354
- }
355
-
356
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTID ] && is_singular() === true ) {
357
- $dataLayer['postID'] = (int) get_the_ID();
358
- }
359
-
360
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTFORMAT ] && is_singular() === true ) {
361
- $dataLayer['postFormat'] = get_post_format() ?: 'standard';
362
- }
363
-
364
- if ( $gtm4wp_options[ GTM4WP_OPTION_BLACKLIST_ENABLE ] > 0 ) {
365
- $_gtmrestrictlistitems = array();
366
-
367
- // because of security reasons, we loop through each stored entity in the options and validate them
368
- // to make sure nobody has entered some 'funny' item manually
369
- $valid_entity_ids = array_merge(
370
- array_keys( $gtm4wp_entity_ids[ 'tags' ] ),
371
- array_keys( $gtm4wp_entity_ids[ 'triggers' ] ),
372
- array_keys( $gtm4wp_entity_ids[ 'variables' ] )
373
- );
374
- foreach( $gtm4wp_options[ GTM4WP_OPTION_BLACKLIST_STATUS ] as $listed_entity ) {
375
- if ( in_array( $listed_entity, $valid_entity_ids ) ) {
376
- $_gtmrestrictlistitems[] = $listed_entity;
377
- }
378
- }
379
-
380
- $_gtmwhitelist = array();
381
- $_gtmblacklist = array();
382
- if ( $gtm4wp_options[ GTM4WP_OPTION_BLACKLIST_ENABLE ] == 1 ) {
383
- $_gtmblacklist = array_merge( $_gtmblacklist, $_gtmrestrictlistitems );
384
- } else {
385
- $_gtmwhitelist = array_merge( $_gtmwhitelist, $_gtmrestrictlistitems );
386
- }
387
-
388
- $dataLayer['gtm.whitelist'] = $_gtmwhitelist;
389
- $dataLayer['gtm.blacklist'] = $_gtmblacklist;
390
- }
391
-
392
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_MISCGEOCF ] && isset( $_SERVER['HTTP_CF_IPCOUNTRY'] ) ) {
393
- $dataLayer['geoCloudflareCountryCode'] = $_SERVER['HTTP_CF_IPCOUNTRY'];
394
- }
395
-
396
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_WEATHER ] || $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_MISCGEO ] ) {
397
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_WEATHER ] ) {
398
- $dataLayer['weatherCategory'] = __( '(no weather data available)', 'duracelltomi-google-tag-manager' );
399
- $dataLayer['weatherDescription'] = __( '(no weather data available)', 'duracelltomi-google-tag-manager' );
400
- $dataLayer['weatherTemp'] = 0;
401
- $dataLayer['weatherPressure'] = 0;
402
- $dataLayer['weatherWindSpeed'] = 0;
403
- $dataLayer['weatherWindDeg'] = 0;
404
- $dataLayer['weatherDataStatus'] = 'Initialized with empty data';
405
- }
406
-
407
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_MISCGEO ] ) {
408
- $dataLayer['geoCountryCode'] = __( '(no geo data available)', 'duracelltomi-google-tag-manager' );
409
- $dataLayer['geoCountryName'] = __( '(no geo data available)', 'duracelltomi-google-tag-manager' );
410
- $dataLayer['geoRegionCode'] = __( '(no geo data available)', 'duracelltomi-google-tag-manager' );
411
- $dataLayer['geoRegionName'] = __( '(no geo data available)', 'duracelltomi-google-tag-manager' );
412
- $dataLayer['geoCity'] = __( '(no geo data available)', 'duracelltomi-google-tag-manager' );
413
- $dataLayer['geoZipcode'] = __( '(no geo data available)', 'duracelltomi-google-tag-manager' );
414
- $dataLayer['geoLatitude'] = __( '(no geo data available)', 'duracelltomi-google-tag-manager' );
415
- $dataLayer['geoLongitude'] = __( '(no geo data available)', 'duracelltomi-google-tag-manager' );
416
- }
417
-
418
- $client_ip = gtm4wp_get_user_ip();
419
-
420
- if ( '' !== $client_ip ) {
421
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_WEATHER ] ) {
422
- $weatherdata = get_transient( 'gtm4wp-weatherdata-' . esc_attr( $client_ip ) );
423
-
424
- if ( false !== $weatherdata ) {
425
- $dataLayer['weatherCategory'] = $weatherdata->weather[0]->main;
426
- $dataLayer['weatherDescription'] = $weatherdata->weather[0]->description;
427
- $dataLayer['weatherTemp'] = $weatherdata->main->temp;
428
- $dataLayer['weatherPressure'] = $weatherdata->main->pressure;
429
- $dataLayer['weatherWindSpeed'] = $weatherdata->wind->speed;
430
- $dataLayer['weatherWindDeg'] = ( isset($weatherdata->wind->deg) ? $weatherdata->wind->deg : '' );
431
- $dataLayer['weatherFullWeatherData'] = $weatherdata;
432
- $dataLayer['weatherDataStatus'] = 'Read from cache';
433
- } else {
434
- $dataLayer['weatherDataStatus'] = 'No weather data in cache (' . esc_attr( $client_ip ) . ')';
435
- }
436
- }
437
-
438
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_MISCGEO ] ) {
439
- $geodata = get_transient( 'gtm4wp-geodata-' . esc_attr( $client_ip ) );
440
-
441
- if ( false !== $geodata ) {
442
- $dataLayer['geoFullGeoData'] = $geodata;
443
-
444
- if ( isset( $geodata->latitude ) ) {
445
- $dataLayer['geoCountryCode'] = $geodata->country_code;
446
- $dataLayer['geoCountryName'] = $geodata->country_name;
447
- $dataLayer['geoRegionCode'] = $geodata->region_code;
448
- $dataLayer['geoRegionName'] = $geodata->region_name;
449
- $dataLayer['geoCity'] = $geodata->city;
450
- $dataLayer['geoZipcode'] = $geodata->zip;
451
- $dataLayer['geoLatitude'] = $geodata->latitude;
452
- $dataLayer['geoLongitude'] = $geodata->longitude;
453
- }
454
- }
455
- }
456
- }
457
- }
458
-
459
- return $dataLayer;
460
- }
461
-
462
- function gtm4wp_wp_loaded() {
463
- global $gtm4wp_options;
464
-
465
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_WEATHER ] || $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_MISCGEO ] ) {
466
- $client_ip = gtm4wp_get_user_ip();
467
- $geodata = get_transient( 'gtm4wp-geodata-' . esc_attr( $client_ip ) );
468
-
469
- if ( false === $geodata ) {
470
- $gtm4wp_geodata = @wp_remote_get( sprintf( 'http://api.ipstack.com/%s?access_key=%s&format=1', urlencode( $client_ip ), $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_MISCGEOAPI ] ) );
471
-
472
- if ( is_array( $gtm4wp_geodata ) && ( 200 == $gtm4wp_geodata['response']['code'] ) ) {
473
- $gtm4wp_geodata = @json_decode( $gtm4wp_geodata['body'] );
474
-
475
- if ( is_object( $gtm4wp_geodata ) ) {
476
- set_transient( 'gtm4wp-geodata-' . esc_attr( $client_ip ), $gtm4wp_geodata, 60 * 60 );
477
-
478
- $weatherdata = get_transient( 'gtm4wp-weatherdata-' . esc_attr( $client_ip ) );
479
- if ( false === $weatherdata && isset( $gtm4wp_geodata->latitude ) ) {
480
-
481
- $weatherdata = wp_remote_get( 'http://api.openweathermap.org/data/2.5/weather?appid=' . $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_WEATHEROWMAPI ] . '&lat=' . $gtm4wp_geodata->latitude . '&lon=' . $gtm4wp_geodata->longitude . '&units=' . ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_WEATHERUNITS ] == 0 ? 'metric' : 'imperial' ) );
482
-
483
- if ( is_array( $weatherdata ) && ( 200 == $weatherdata['response']['code'] ) ) {
484
- $weatherdata = @json_decode( $weatherdata['body'] );
485
-
486
- if ( is_object( $weatherdata ) ) {
487
- set_transient( 'gtm4wp-weatherdata-' . esc_attr( $client_ip ), $weatherdata, 60 * 60 );
488
- setcookie( 'gtm4wp_last_weatherstatus', 'Weather data loaded.' );
489
- } else {
490
- setcookie( 'gtm4wp_last_weatherstatus', 'Openweathermap.org did not return processable data: ' . var_export( $weatherdata, true ) );
491
- }
492
- } else {
493
- if ( is_wp_error( $weatherdata ) ) {
494
- setcookie( 'gtm4wp_last_weatherstatus', 'Openweathermap.org request error: ' . $weatherdata->get_error_message() );
495
- } else {
496
- setcookie( 'gtm4wp_last_weatherstatus', 'Openweathermap.org returned status code: ' . $weatherdata['response']['code'] );
497
- }
498
- }
499
- }
500
- } else {
501
- setcookie( 'gtm4wp_last_weatherstatus', 'ipstack.com did not return lat-lng data: ' . var_export( $gtm4wp_geodata, true ) );
502
- }
503
- } else {
504
- if ( is_wp_error( $gtm4wp_geodata ) ) {
505
- setcookie( 'gtm4wp_last_weatherstatus', 'ipstack.com request error: ' . $gtm4wp_geodata->get_error_message() );
506
- } else {
507
- setcookie( 'gtm4wp_last_weatherstatus', 'ipstack.com returned status code: ' . $gtm4wp_geodata['response']['code'] );
508
- }
509
- }
510
- }
511
- }
512
- }
513
-
514
- function gtm4wp_get_the_gtm_tag() {
515
- global $gtm4wp_options, $gtm4wp_datalayer_name, $gtm4wp_container_code_written;
516
-
517
- $_gtm_tag = '
518
- <!-- Google Tag Manager (noscript) -->';
519
-
520
- if ( GTM4WP_PLACEMENT_OFF == $gtm4wp_options[ GTM4WP_OPTION_GTM_PLACEMENT ] ) {
521
- $gtm4wp_container_code_written = true;
522
- }
523
-
524
- if ( ( $gtm4wp_options[ GTM4WP_OPTION_GTM_CODE ] != '' ) && ( ! $gtm4wp_container_code_written ) ) {
525
- $_gtm_codes = explode( ',', str_replace( array( ';', ' ' ), array( ',', '' ), $gtm4wp_options[ GTM4WP_OPTION_GTM_CODE ] ) );
526
-
527
- if ( ( '' != $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_AUTH ] ) && ( '' != $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_PREVIEW ] ) ) {
528
- $_gtm_env = '&gtm_auth=' . $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_AUTH ] . '&gtm_preview=' . $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_PREVIEW ] . '&gtm_cookies_win=x';
529
- } else {
530
- $_gtm_env = '';
531
- }
532
-
533
- $_gtm_domain_name = 'www.googletagmanager.com';
534
- if ( $gtm4wp_options[ GTM4WP_OPTION_GTMDOMAIN ] != '' ) {
535
- $_gtm_domain_name = $gtm4wp_options[ GTM4WP_OPTION_GTMDOMAIN ];
536
- }
537
-
538
- foreach ( $_gtm_codes as $one_gtm_code ) {
539
- $_gtm_tag .= '
540
- <noscript><iframe src="https://' . $_gtm_domain_name . '/ns.html?id=' . $one_gtm_code . $_gtm_env . '"
541
- height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>';
542
- }
543
-
544
- $_gtm_tag .= '
545
- <!-- End Google Tag Manager (noscript) -->';
546
-
547
- $_gtm_tag = apply_filters( GTM4WP_WPFILTER_GETTHEGTMTAG, $_gtm_tag );
548
- $gtm4wp_container_code_written = true;
549
- }
550
-
551
- return $_gtm_tag;
552
- }
553
-
554
- function gtm4wp_the_gtm_tag() {
555
- echo gtm4wp_get_the_gtm_tag();
556
- }
557
-
558
- function gtm4wp_enqueue_scripts() {
559
- global $gtm4wp_options, $gtp4wp_plugin_url;
560
-
561
- if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WPCF7 ] ) {
562
- $in_footer = apply_filters( 'gtm4wp_' . GTM4WP_OPTION_INTEGRATE_WPCF7, false );
563
- wp_enqueue_script( 'gtm4wp-contact-form-7-tracker', $gtp4wp_plugin_url . 'js/gtm4wp-contact-form-7-tracker.js', array( 'jquery' ), GTM4WP_VERSION, $in_footer );
564
- }
565
-
566
- if ( $gtm4wp_options[ GTM4WP_OPTION_EVENTS_FORMMOVE ] ) {
567
- $in_footer = apply_filters( 'gtm4wp_' . GTM4WP_OPTION_EVENTS_FORMMOVE, false );
568
- wp_enqueue_script( 'gtm4wp-form-move-tracker', $gtp4wp_plugin_url . 'js/gtm4wp-form-move-tracker.js', array( 'jquery' ), GTM4WP_VERSION, $in_footer );
569
- }
570
-
571
- if ( $gtm4wp_options[ GTM4WP_OPTION_EVENTS_YOUTUBE ] ) {
572
- require_once dirname( __FILE__ ) . '/../integration/youtube.php';
573
- }
574
-
575
- if ( $gtm4wp_options[ GTM4WP_OPTION_EVENTS_VIMEO ] ) {
576
- require_once dirname( __FILE__ ) . '/../integration/vimeo.php';
577
- }
578
-
579
- if ( $gtm4wp_options[ GTM4WP_OPTION_EVENTS_SOUNDCLOUD ] ) {
580
- require_once dirname( __FILE__ ) . '/../integration/soundcloud.php';
581
- }
582
-
583
- if ( $gtm4wp_options[ GTM4WP_OPTION_SCROLLER_ENABLED ] ) {
584
- $in_footer = apply_filters( 'gtm4wp_' . GTM4WP_OPTION_SCROLLER_ENABLED, false );
585
- wp_enqueue_script( 'gtm4wp-scroll-tracking', $gtp4wp_plugin_url . 'js/analytics-talk-content-tracking.js', array( 'jquery' ), GTM4WP_VERSION, $in_footer );
586
- }
587
- }
588
-
589
- function gtm4wp_wp_footer() {
590
- global $gtm4wp_options;
591
-
592
- if ( GTM4WP_PLACEMENT_FOOTER == $gtm4wp_options[ GTM4WP_OPTION_GTM_PLACEMENT ] ) {
593
- gtm4wp_the_gtm_tag();
594
- }
595
- }
596
-
597
- function gtm4wp_wp_body_open() {
598
- global $gtm4wp_options;
599
-
600
- if ( ( GTM4WP_PLACEMENT_BODYOPEN == $gtm4wp_options[ GTM4WP_OPTION_GTM_PLACEMENT ] ) || ( GTM4WP_PLACEMENT_BODYOPEN_AUTO == $gtm4wp_options[ GTM4WP_OPTION_GTM_PLACEMENT ] ) ) {
601
- gtm4wp_the_gtm_tag();
602
- }
603
- }
604
-
605
- function gtm4wp_filter_visitor_keys( $dataLayer ) {
606
- foreach ( $dataLayer as $dl_key => $dl_value ) {
607
- if ( strpos( $dl_key, 'visitor' ) !== false ) {
608
- unset( $dataLayer[ $dl_key ] );
609
- }
610
- }
611
-
612
- return $dataLayer;
613
- }
614
-
615
- /**
616
- * GTM4WP global JS variables WordPress filter
617
- *
618
- * @author Vincent Koc <https://github.com/koconder/>
619
- * @link https://github.com/duracelltomi/gtm4wp/issues/34
620
- * @return mixed returns the
621
- */
622
- function gtm4wp_add_global_vars( $vars, $return = false ) {
623
- if ( ! $return ) {
624
- if ( function_exists( $vars ) ) {
625
- $vars = $vars();
626
- }
627
- $GLOBALS['gtm4wp_datalayer_globalvars'] = $GLOBALS['gtm4wp_datalayer_globalvars'] . ' ' . $vars;
628
- }
629
- return $GLOBALS['gtm4wp_datalayer_globalvars'];
630
- }
631
-
632
- function gtm4wp_wp_header_top( $echo = true ) {
633
- global $gtm4wp_options, $gtm4wp_datalayer_name;
634
-
635
- $has_html5_support = current_theme_supports( 'html5' );
636
-
637
- $_gtm_top_content = '
638
- <!-- Google Tag Manager for WordPress by gtm4wp.com -->
639
- <script data-cfasync="false" data-pagespeed-no-defer' . ( $has_html5_support ? ' type="text/javascript"' : '' ) . '>//<![CDATA[
640
- var gtm4wp_datalayer_name = "' . $gtm4wp_datalayer_name . '";
641
- var ' . $gtm4wp_datalayer_name . ' = ' . $gtm4wp_datalayer_name . ' || [];';
642
-
643
- // Load in the global variables from gtm4wp_add_global_vars / GTM4WP_WPACTION_ADDGLOBALVARS filter
644
- $_gtm_top_content .= apply_filters( GTM4WP_WPACTION_ADDGLOBALVARS, '', true );
645
-
646
- if ( $gtm4wp_options[ GTM4WP_OPTION_SCROLLER_ENABLED ] ) {
647
- $_gtm_top_content .= '
648
-
649
- var gtm4wp_scrollerscript_debugmode = ' . ( $gtm4wp_options[ GTM4WP_OPTION_SCROLLER_DEBUGMODE ] ? 'true' : 'false' ) . ';
650
- var gtm4wp_scrollerscript_callbacktime = ' . (int) $gtm4wp_options[ GTM4WP_OPTION_SCROLLER_CALLBACKTIME ] . ';
651
- var gtm4wp_scrollerscript_readerlocation = ' . (int) $gtm4wp_options[ GTM4WP_OPTION_SCROLLER_DISTANCE ] . ';
652
- var gtm4wp_scrollerscript_contentelementid = "' . $gtm4wp_options[ GTM4WP_OPTION_SCROLLER_CONTENTID ] . '";
653
- var gtm4wp_scrollerscript_scannertime = ' . (int) $gtm4wp_options[ GTM4WP_OPTION_SCROLLER_READERTIME ] . ';';
654
- }
655
-
656
- $_gtm_top_content .= '
657
- //]]>
658
- </script>
659
- <!-- End Google Tag Manager for WordPress by gtm4wp.com -->';
660
-
661
- if ( ! gtm4wp_amp_running() ) {
662
- if ( $echo ) {
663
- echo $_gtm_top_content;
664
- } else {
665
- return $_gtm_top_content;
666
- }
667
- }
668
- }
669
-
670
- function gtm4wp_wp_header_begin( $echo = true ) {
671
- global $gtm4wp_datalayer_name, $gtm4wp_datalayer_json, $gtm4wp_options, $woocommerce;
672
-
673
- $has_html5_support = current_theme_supports( 'html5' );
674
-
675
- $_gtm_header_content = '
676
- <!-- Google Tag Manager for WordPress by gtm4wp.com -->
677
- <script data-cfasync="false" data-pagespeed-no-defer' . ( $has_html5_support ? ' type="text/javascript"' : '' ) . '>//<![CDATA[';
678
-
679
- if ( $gtm4wp_options[ GTM4WP_OPTION_GTM_CODE ] != '' ) {
680
- $gtm4wp_datalayer_data = array();
681
- $gtm4wp_datalayer_data = (array) apply_filters( GTM4WP_WPFILTER_COMPILE_DATALAYER, $gtm4wp_datalayer_data );
682
-
683
- if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_REMARKETING ] ) {
684
- // add Google Ads remarketing tags as suggested here:
685
- // https://support.google.com/tagmanager/answer/3002580?hl=en
686
- add_filter( GTM4WP_WPFILTER_COMPILE_REMARKTING, 'gtm4wp_filter_visitor_keys' );
687
- $gtm4wp_remarketing_tags = (array) apply_filters( GTM4WP_WPFILTER_COMPILE_REMARKTING, $gtm4wp_datalayer_data );
688
-
689
- $_gtm_header_content .= "\nvar google_tag_params = ";
690
- $_gtm_header_content .= json_encode( $gtm4wp_remarketing_tags );
691
- $_gtm_header_content .= ';';
692
- $gtm4wp_datalayer_data['google_tag_params'] = '-~-window.google_tag_params-~-';
693
- }
694
-
695
- if ( version_compare( PHP_VERSION, '5.4.0' ) >= 0 ) {
696
- $gtm4wp_datalayer_json = json_encode( $gtm4wp_datalayer_data, JSON_UNESCAPED_UNICODE );
697
- } else {
698
- $gtm4wp_datalayer_json = json_encode( $gtm4wp_datalayer_data );
699
- }
700
-
701
- // Clean up and then push datalayer to AMP
702
- $gtm4wp_datalayer_json = str_replace(
703
- array( '"-~-', '-~-"' ),
704
- array( '', '' ),
705
- str_replace( '–', '-', $gtm4wp_datalayer_json )
706
- );
707
-
708
- $_gtm_header_content .= '
709
- var dataLayer_content = ' . $gtm4wp_datalayer_json . ';';
710
-
711
- // fire WooCommerce order double tracking protection only if WooCommerce is active and user is on the order received page
712
- if ( isset( $gtm4wp_options ) && ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKCLASSICEC ] || $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) && isset( $woocommerce ) && is_order_received_page() ) {
713
-
714
- $_gtm_header_content .= '
715
- // if dataLayer contains ecommerce purchase data, check whether it has been already tracked
716
- if ( dataLayer_content.transactionId || ( dataLayer_content.ecommerce && dataLayer_content.ecommerce.purchase ) ) {
717
- // read order id already tracked from cookies
718
- var gtm4wp_orderid_tracked = "";
719
-
720
- if ( !window.localStorage ) {
721
- var gtm4wp_cookie = "; " + document.cookie;
722
- var gtm4wp_cookie_parts = gtm4wp_cookie.split( "; gtm4wp_orderid_tracked=" );
723
- if ( gtm4wp_cookie_parts.length == 2 ) {
724
- gtm4wp_orderid_tracked = gtm4wp_cookie_parts.pop().split(";").shift();
725
- }
726
- } else {
727
- gtm4wp_orderid_tracked = window.localStorage.getItem( "gtm4wp_orderid_tracked" );
728
- }
729
-
730
- // check enhanced ecommerce
731
- if ( dataLayer_content.ecommerce && dataLayer_content.ecommerce.purchase ) {
732
- if ( gtm4wp_orderid_tracked && ( dataLayer_content.ecommerce.purchase.actionField.id == gtm4wp_orderid_tracked ) ) {
733
- delete dataLayer_content.ecommerce.purchase;
734
- } else {
735
- gtm4wp_orderid_tracked = dataLayer_content.ecommerce.purchase.actionField.id;
736
- }
737
- }
738
-
739
- // check app+web ecommerce
740
- if ( dataLayer_content.ecommerce && dataLayer_content.ecommerce.items ) {
741
- if ( gtm4wp_orderid_tracked && ( dataLayer_content.ecommerce.transaction_id == gtm4wp_orderid_tracked ) ) {
742
- delete dataLayer_content.ecommerce.affiliation;
743
- delete dataLayer_content.ecommerce.value;
744
- delete dataLayer_content.ecommerce.currency;
745
- delete dataLayer_content.ecommerce.tax;
746
- delete dataLayer_content.ecommerce.shipping;
747
- delete dataLayer_content.ecommerce.transaction_id;
748
-
749
- delete dataLayer_content.ecommerce.items;
750
- } else {
751
- gtm4wp_orderid_tracked = dataLayer_content.ecommerce.purchase.actionField.id;
752
- }
753
- }
754
-
755
- // check standard ecommerce
756
- if ( dataLayer_content.transactionId ) {
757
- if ( gtm4wp_orderid_tracked && ( dataLayer_content.transactionId == gtm4wp_orderid_tracked ) ) {
758
- delete dataLayer_content.transactionId;
759
- delete dataLayer_content.transactionDate;
760
- delete dataLayer_content.transactionType;
761
- delete dataLayer_content.transactionAffiliation;
762
- delete dataLayer_content.transactionTotal;
763
- delete dataLayer_content.transactionShipping;
764
- delete dataLayer_content.transactionTax;
765
- delete dataLayer_content.transactionPaymentType;
766
- delete dataLayer_content.transactionCurrency;
767
- delete dataLayer_content.transactionShippingMethod;
768
- delete dataLayer_content.transactionPromoCode;
769
- delete dataLayer_content.transactionProducts;
770
- } else {
771
- gtm4wp_orderid_tracked = dataLayer_content.transactionId;
772
- }
773
- }
774
-
775
- if ( gtm4wp_orderid_tracked ) {
776
- if ( !window.localStorage ) {
777
- var gtm4wp_orderid_cookie_expire = new Date();
778
- gtm4wp_orderid_cookie_expire.setTime( gtm4wp_orderid_cookie_expire.getTime() + (365*24*60*60*1000) );
779
- var gtm4wp_orderid_cookie_expires_part = "expires=" + gtm4wp_orderid_cookie_expire.toUTCString();
780
- document.cookie = "gtm4wp_orderid_tracked=" + gtm4wp_orderid_tracked + ";" + gtm4wp_orderid_cookie_expires_part + ";path=/";
781
- } else {
782
- window.localStorage.setItem( "gtm4wp_orderid_tracked", gtm4wp_orderid_tracked );
783
- }
784
- }
785
-
786
- }';
787
- }
788
-
789
- $_gtm_header_content .= '
790
- ' . $gtm4wp_datalayer_name . '.push( dataLayer_content );';
791
- }
792
-
793
- $_gtm_header_content .= '//]]>
794
- </script>';
795
-
796
- $_gtm_header_content .= apply_filters( GTM4WP_WPFILTER_AFTER_DATALAYER, '' );
797
-
798
- if ( ( $gtm4wp_options[ GTM4WP_OPTION_GTM_CODE ] != '' ) && ( GTM4WP_PLACEMENT_OFF != $gtm4wp_options[ GTM4WP_OPTION_GTM_PLACEMENT ] ) ) {
799
- $_gtm_codes = explode( ',', str_replace( array( ';', ' ' ), array( ',', '' ), $gtm4wp_options[ GTM4WP_OPTION_GTM_CODE ] ) );
800
- $add_cookiebot_ignore = $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_COOKIEBOT ];
801
-
802
- $_gtm_tag = '';
803
- foreach ( $_gtm_codes as $one_gtm_code ) {
804
- if ( ( '' != $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_AUTH ] ) && ( '' != $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_PREVIEW ] ) ) {
805
- $_gtm_env = "+'&gtm_auth=" . $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_AUTH ] . '&gtm_preview=' . $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_PREVIEW ] . "&gtm_cookies_win=x'";
806
- } else {
807
- $_gtm_env = '';
808
- }
809
-
810
- $_gtm_domain_name = 'www.googletagmanager.com';
811
- if ( $gtm4wp_options[ GTM4WP_OPTION_GTMDOMAIN ] != '' ) {
812
- $_gtm_domain_name = $gtm4wp_options[ GTM4WP_OPTION_GTMDOMAIN ];
813
- }
814
-
815
- $_gtm_tag .= '
816
- <script data-cfasync="false"' . ( $add_cookiebot_ignore ? ' data-cookieconsent="ignore"' : '' ) . '>//<![CDATA[
817
- (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({\'gtm.start\':
818
- new Date().getTime(),event:\'gtm.js\'});var f=d.getElementsByTagName(s)[0],
819
- j=d.createElement(s),dl=l!=\'dataLayer\'?\'&l=\'+l:\'\';j.async=true;j.src=
820
- \'//' . $_gtm_domain_name . '/gtm.\'' . '+\'js?id=\'+i+dl' . $_gtm_env . ';f.parentNode.insertBefore(j,f);
821
- })(window,document,\'script\',\'' . $gtm4wp_datalayer_name . '\',\'' . $one_gtm_code . '\');//]]>
822
- </script>';
823
- }
824
-
825
- $_gtm_tag .= '
826
- <!-- End Google Tag Manager -->';
827
-
828
- $_gtm_tag = apply_filters( GTM4WP_WPFILTER_GETTHEGTMTAG, $_gtm_tag );
829
- $_gtm_header_content .= $_gtm_tag;
830
- }
831
-
832
- $_gtm_header_content .= '
833
- <!-- End Google Tag Manager for WordPress by gtm4wp.com -->';
834
-
835
- if ( ! gtm4wp_amp_running() ) {
836
- if ( $echo ) {
837
- echo $_gtm_header_content;
838
- } else {
839
- return $_gtm_header_content;
840
- }
841
- }
842
- }
843
-
844
- function gtm4wp_wp_login() {
845
- setcookie( 'gtm4wp_user_logged_in', '1', 0, '/' );
846
- }
847
-
848
- function gtm4wp_user_register() {
849
- setcookie( 'gtm4wp_user_registered', '1', 0, '/' );
850
- }
851
-
852
- function gtm4wp_user_reg_login_script() {
853
- global $gtp4wp_plugin_url;
854
-
855
- $in_footer = apply_filters( 'gtm4wp_user_reg_login_script', true );
856
- wp_enqueue_script( 'gtm4wp-user-reg-login-script', $gtp4wp_plugin_url . 'js/gtm4wp-users.js', array( 'jquery' ), GTM4WP_VERSION, $in_footer );
857
- }
858
-
859
- function gtm4wp_rocket_excluded_inline_js_content( $pattern ) {
860
- $pattern[] = 'dataLayer';
861
- $pattern[] = 'gtm4wp';
862
-
863
- return $pattern;
864
- }
865
-
866
- add_action( 'wp_enqueue_scripts', 'gtm4wp_enqueue_scripts' );
867
- $gtm4wp_header_begin_prior = 10;
868
- if ( isset( $GLOBALS['gtm4wp_options'] ) && $GLOBALS['gtm4wp_options'][ GTM4WP_OPTION_LOADEARLY ] ) {
869
- $gtm4wp_header_begin_prior = 2;
870
- }
871
- add_action( 'wp_head', 'gtm4wp_wp_header_begin', $gtm4wp_header_begin_prior, 0 );
872
- add_action( 'wp_head', 'gtm4wp_wp_header_top', 1, 0 );
873
- add_action( 'wp_footer', 'gtm4wp_wp_footer' );
874
- add_action( 'wp_loaded', 'gtm4wp_wp_loaded' );
875
- add_filter( GTM4WP_WPFILTER_COMPILE_DATALAYER, 'gtm4wp_add_basic_datalayer_data' );
876
-
877
- // to be able to easily migrate from other Google Tag Manager plugins
878
- add_action( 'body_open', 'gtm4wp_wp_body_open' );
879
-
880
- // compatibility with existing themes that natively support code injection after opening body tag
881
- add_action( 'genesis_before', 'gtm4wp_wp_body_open' ); // Genisis theme
882
- add_action( 'generate_before_header', 'gtm4wp_wp_body_open', 0 ); // GeneratePress theme
883
- add_action( 'elementor/page_templates/canvas/before_content', 'gtm4wp_wp_body_open' ); // Elementor
884
- add_action( 'ct_before_builder', 'gtm4wp_wp_body_open', 0 ); // Oxygen Builder
885
- add_action( 'fl_before_builder', 'gtm4wp_wp_body_open', 0 ); // Beaver Builder Theme
886
-
887
- // standard WP theme support for body open tags
888
- add_action( 'wp_body_open', 'gtm4wp_wp_body_open' );
889
-
890
- add_filter( 'rocket_excluded_inline_js_content', 'gtm4wp_rocket_excluded_inline_js_content' ); // WP Rocket
891
- if (
892
- isset( $GLOBALS['gtm4wp_options'] )
893
- && (
894
- $GLOBALS['gtm4wp_options'][ GTM4WP_OPTION_INTEGRATE_WCTRACKCLASSICEC ]
895
- || $GLOBALS['gtm4wp_options'][ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ]
896
- )
897
- && isset( $GLOBALS['woocommerce'] )
898
- && version_compare( WC()->version, '3.2', '>=' ) // only activate WooCommerce integration for minimum supported WooCommerce version
899
- ) {
900
- require_once dirname( __FILE__ ) . '/../integration/woocommerce.php';
901
- }
902
-
903
- if ( isset( $GLOBALS['gtm4wp_options'] ) && ( $GLOBALS['gtm4wp_options'][ GTM4WP_OPTION_INTEGRATE_GOOGLEOPTIMIZEIDS ] != '' ) ) {
904
- require_once dirname( __FILE__ ) . '/../integration/google-optimize.php';
905
- }
906
-
907
- if ( isset( $GLOBALS['gtm4wp_options'] ) && ( $GLOBALS['gtm4wp_options'][ GTM4WP_OPTION_EVENTS_USERLOGIN ] ) ) {
908
- add_action( 'wp_login', 'gtm4wp_wp_login' );
909
- add_action( 'wp_enqueue_scripts', 'gtm4wp_user_reg_login_script' );
910
- }
911
-
912
- if ( isset( $GLOBALS['gtm4wp_options'] ) && ( $GLOBALS['gtm4wp_options'][ GTM4WP_OPTION_EVENTS_NEWUSERREG ] ) ) {
913
- add_action( 'user_register', 'gtm4wp_user_register' );
914
- add_action( 'wp_enqueue_scripts', 'gtm4wp_user_reg_login_script' );
915
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ define( 'GTM4WP_WPFILTER_COMPILE_DATALAYER', 'gtm4wp_compile_datalayer' );
3
+ define( 'GTM4WP_WPFILTER_COMPILE_REMARKTING', 'gtm4wp_compile_remarkering' );
4
+ define( 'GTM4WP_WPFILTER_AFTER_DATALAYER', 'gtm4wp_after_datalayer' );
5
+ define( 'GTM4WP_WPFILTER_GETTHEGTMTAG', 'gtm4wp_get_the_gtm_tag' );
6
+ define( 'GTM4WP_WPFILTER_ADDGLOBALVARS', 'gtm4wp_add_global_vars' );
7
+
8
+ $GLOBALS['gtm4wp_container_code_written'] = false;
9
+
10
+ // check for empty is needed to prevent error in WP CLI
11
+ // bugfix by Patrick Holberg Hesselberg
12
+ if ( empty( $GLOBALS['gtm4wp_options'] ) || ( $GLOBALS['gtm4wp_options'][ GTM4WP_OPTION_DATALAYER_NAME ] == '' ) ) {
13
+ $GLOBALS['gtm4wp_datalayer_name'] = 'dataLayer';
14
+ } else {
15
+ $GLOBALS['gtm4wp_datalayer_name'] = $GLOBALS['gtm4wp_options'][ GTM4WP_OPTION_DATALAYER_NAME ];
16
+ }
17
+
18
+ // Setting Global Variable to Store JSON based Datalayer for Intergrations
19
+ $GLOBALS['gtm4wp_datalayer_json'] = '';
20
+ $GLOBALS['gtm4wp_datalayer_globalvars'] = '';
21
+
22
+ // Moving include to top due to hierarchy of includes
23
+ if ( isset( $GLOBALS['gtm4wp_options'] ) && ( '' != $GLOBALS['gtm4wp_options'][ GTM4WP_OPTION_INTEGRATE_AMPID ] ) ) {
24
+ require_once dirname( __FILE__ ) . '/../integration/amp.php';
25
+ }
26
+ if ( ! function_exists( 'gtm4wp_amp_running' ) ) {
27
+ function gtm4wp_amp_running() {
28
+ return false;
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Converts bool false to string false for JS
34
+ *
35
+ * @author Vincent Koc <https://github.com/koconder/>
36
+ * @return mixed Returs object or string false
37
+ */
38
+ function gtm4wp_escjs_boolean( $obj ) {
39
+ if ( empty( $obj ) || is_null( $obj ) || ! $obj ) {
40
+ return 'false';
41
+ } else {
42
+ return $obj;
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Original copyright:
48
+ * By Grant Burton @ BURTONTECH.COM
49
+ *
50
+ * Code improved by Thomas Geiger
51
+ */
52
+ function gtm4wp_get_user_ip() {
53
+ if ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
54
+ foreach ( explode( ',', $_SERVER['HTTP_X_FORWARDED_FOR'] ) as $ip ) {
55
+ if ( filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) !== false ) {
56
+ return $ip;
57
+ }
58
+ }
59
+ }
60
+
61
+ $possible_ip_variables = array(
62
+ 'HTTP_CLIENT_IP',
63
+ 'HTTP_X_FORWARDED',
64
+ 'HTTP_X_CLUSTER_CLIENT_IP',
65
+ 'HTTP_FORWARDED_FOR',
66
+ 'HTTP_FORWARDED',
67
+ 'REMOTE_ADDR'
68
+ );
69
+
70
+ foreach( $possible_ip_variables as $one_ip_variable ) {
71
+ if (
72
+ ! empty( $_SERVER[ $one_ip_variable ] )
73
+ && ( filter_var( $_SERVER[ $one_ip_variable ], FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) !== false )
74
+ ) {
75
+ return $_SERVER[ $one_ip_variable ];
76
+ }
77
+ }
78
+
79
+ return '';
80
+ }
81
+
82
+ if ( ! function_exists( 'getallheaders' ) ) {
83
+ function getallheaders() {
84
+ $headers = array();
85
+ foreach ( $_SERVER as $name => $value ) {
86
+ if ( substr( $name, 0, 5 ) == 'HTTP_' ) {
87
+ $headers[ str_replace( ' ', '-', ucwords( strtolower( str_replace( '_', ' ', substr( $name, 5 ) ) ) ) ) ] = $value;
88
+ }
89
+ }
90
+
91
+ return $headers;
92
+ }
93
+ }
94
+
95
+ function gtm4wp_add_basic_datalayer_data( $dataLayer ) {
96
+ global $wp_query, $gtm4wp_options, $gtm4wp_entity_ids;
97
+
98
+ if ( $gtm4wp_options[ GTM4WP_OPTION_DONOTTRACK ] ) {
99
+ if ( ! empty( $_SERVER['HTTP_DNT'] ) ) {
100
+ $dataLayer['visitorDoNotTrack'] = (int) ( $_SERVER['HTTP_DNT'] );
101
+ } else {
102
+ $dataLayer['visitorDoNotTrack'] = 0;
103
+ }
104
+ }
105
+
106
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_SITEID ] || $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_SITENAME ] ) {
107
+ $dataLayer['siteID'] = 0;
108
+ $dataLayer['siteName'] = '';
109
+
110
+ if ( function_exists( 'get_blog_details' ) ) {
111
+ $gtm4wp_blogdetails = get_blog_details();
112
+
113
+ $dataLayer['siteID'] = $gtm4wp_blogdetails->blog_id;
114
+ $dataLayer['siteName'] = $gtm4wp_blogdetails->blogname;
115
+ }
116
+ }
117
+
118
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_LOGGEDIN ] ) {
119
+ if ( is_user_logged_in() ) {
120
+ $dataLayer['visitorLoginState'] = 'logged-in';
121
+ } else {
122
+ $dataLayer['visitorLoginState'] = 'logged-out';
123
+ }
124
+ }
125
+
126
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_USERROLE ] || $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_USEREMAIL ] || $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_USERREGDATE ] || $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_USERNAME ] ) {
127
+ $current_user = wp_get_current_user();
128
+
129
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_USERROLE ] ) {
130
+ $dataLayer['visitorType'] = ( $current_user->ID == 0 ? 'visitor-logged-out' : implode(",", $current_user->roles) );
131
+ }
132
+
133
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_USEREMAIL ] ) {
134
+ $dataLayer['visitorEmail'] = ( empty( $current_user->user_email ) ? '' : $current_user->user_email );
135
+ $dataLayer['visitorEmailHash'] = ( empty( $current_user->user_email ) ? '' : hash( 'sha256', $current_user->user_email ) );
136
+ }
137
+
138
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_USERREGDATE ] ) {
139
+ $dataLayer['visitorRegistrationDate'] = ( empty( $current_user->user_registered ) ? '' : strtotime( $current_user->user_registered ) );
140
+ }
141
+
142
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_USERNAME ] ) {
143
+ $dataLayer['visitorUsername'] = ( empty( $current_user->user_login ) ? '' : $current_user->user_login );
144
+ }
145
+ }
146
+
147
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_USERID ] ) {
148
+ $_gtm4wp_userid = get_current_user_id();
149
+ if ( $_gtm4wp_userid > 0 ) {
150
+ $dataLayer['visitorId'] = $_gtm4wp_userid;
151
+ }
152
+ }
153
+
154
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_VISITOR_IP ] ) {
155
+ $dataLayer['visitorIP'] = esc_js( gtm4wp_get_user_ip() );
156
+ }
157
+
158
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTTITLE ] ) {
159
+ $dataLayer['pageTitle'] = strip_tags( wp_title( '|', false, 'right' ) );
160
+ }
161
+
162
+ if ( is_singular() ) {
163
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTTYPE ] ) {
164
+ $dataLayer['pagePostType'] = get_post_type();
165
+ $dataLayer['pagePostType2'] = 'single-' . get_post_type();
166
+ }
167
+
168
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_CATEGORIES ] ) {
169
+ $_post_cats = get_the_category();
170
+ if ( $_post_cats ) {
171
+ $dataLayer['pageCategory'] = array();
172
+ foreach ( $_post_cats as $_one_cat ) {
173
+ $dataLayer['pageCategory'][] = $_one_cat->slug;
174
+ }
175
+ }
176
+ }
177
+
178
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_TAGS ] ) {
179
+ $_post_tags = get_the_tags();
180
+ if ( $_post_tags ) {
181
+ $dataLayer['pageAttributes'] = array();
182
+ foreach ( $_post_tags as $_one_tag ) {
183
+ $dataLayer['pageAttributes'][] = $_one_tag->slug;
184
+ }
185
+ }
186
+ }
187
+
188
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_AUTHORID ] || $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_AUTHOR ] ) {
189
+ $postuser = get_userdata( $GLOBALS['post']->post_author );
190
+
191
+ if ( false !== $postuser ) {
192
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_AUTHORID ] ) {
193
+ $dataLayer['pagePostAuthorID'] = $postuser->ID;
194
+ }
195
+
196
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_AUTHOR ] ) {
197
+ $dataLayer['pagePostAuthor'] = $postuser->display_name;
198
+ }
199
+ }
200
+ }
201
+
202
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTDATE ] ) {
203
+ $dataLayer['pagePostDate'] = get_the_date();
204
+ $dataLayer['pagePostDateYear'] = get_the_date( 'Y' );
205
+ $dataLayer['pagePostDateMonth'] = get_the_date( 'm' );
206
+ $dataLayer['pagePostDateDay'] = get_the_date( 'd' );
207
+ }
208
+
209
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTTERMLIST ] ) {
210
+ $dataLayer["pagePostTerms"] = array();
211
+ $object_taxonomies = get_object_taxonomies( get_post_type() );
212
+ foreach( $object_taxonomies as $one_object_taxonomy ) {
213
+ $post_taxonomy_values = get_the_terms( $GLOBALS[ "post" ]->ID, $one_object_taxonomy );
214
+ if ( is_array( $post_taxonomy_values ) ) {
215
+ $dataLayer["pagePostTerms"][$one_object_taxonomy] = array();
216
+ foreach( $post_taxonomy_values as $one_taxonomy_value ) {
217
+ $dataLayer["pagePostTerms"][$one_object_taxonomy][] = $one_taxonomy_value->name;
218
+ }
219
+ }
220
+ }
221
+ }
222
+ }
223
+
224
+ if ( is_archive() || is_post_type_archive() ) {
225
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTTYPE ] ) {
226
+ $dataLayer['pagePostType'] = get_post_type();
227
+
228
+ if ( is_category() ) {
229
+ $dataLayer['pagePostType2'] = 'category-' . get_post_type();
230
+ } elseif ( is_tag() ) {
231
+ $dataLayer['pagePostType2'] = 'tag-' . get_post_type();
232
+ } elseif ( is_tax() ) {
233
+ $dataLayer['pagePostType2'] = 'tax-' . get_post_type();
234
+ } elseif ( is_author() ) {
235
+ $dataLayer['pagePostType2'] = 'author-' . get_post_type();
236
+ } elseif ( is_year() ) {
237
+ $dataLayer['pagePostType2'] = 'year-' . get_post_type();
238
+
239
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTDATE ] ) {
240
+ $dataLayer['pagePostDateYear'] = get_the_date( 'Y' );
241
+ }
242
+ } elseif ( is_month() ) {
243
+ $dataLayer['pagePostType2'] = 'month-' . get_post_type();
244
+
245
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTDATE ] ) {
246
+ $dataLayer['pagePostDateYear'] = get_the_date( 'Y' );
247
+ $dataLayer['pagePostDateMonth'] = get_the_date( 'm' );
248
+ }
249
+ } elseif ( is_day() ) {
250
+ $dataLayer['pagePostType2'] = 'day-' . get_post_type();
251
+
252
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTDATE ] ) {
253
+ $dataLayer['pagePostDate'] = get_the_date();
254
+ $dataLayer['pagePostDateYear'] = get_the_date( 'Y' );
255
+ $dataLayer['pagePostDateMonth'] = get_the_date( 'm' );
256
+ $dataLayer['pagePostDateDay'] = get_the_date( 'd' );
257
+ }
258
+ } elseif ( is_time() ) {
259
+ $dataLayer['pagePostType2'] = 'time-' . get_post_type();
260
+ } elseif ( is_date() ) {
261
+ $dataLayer['pagePostType2'] = 'date-' . get_post_type();
262
+
263
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTDATE ] ) {
264
+ $dataLayer['pagePostDate'] = get_the_date();
265
+ $dataLayer['pagePostDateYear'] = get_the_date( 'Y' );
266
+ $dataLayer['pagePostDateMonth'] = get_the_date( 'm' );
267
+ $dataLayer['pagePostDateDay'] = get_the_date( 'd' );
268
+ }
269
+ }
270
+ }
271
+
272
+ if ( ( is_tax() || is_category() ) && $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_CATEGORIES ] ) {
273
+ $_post_cats = get_the_category();
274
+ $dataLayer['pageCategory'] = array();
275
+ foreach ( $_post_cats as $_one_cat ) {
276
+ $dataLayer['pageCategory'][] = $_one_cat->slug;
277
+ }
278
+ }
279
+
280
+ if ( ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_AUTHORID ] ) && ( is_author() ) ) {
281
+ global $authordata;
282
+ $dataLayer['pagePostAuthorID'] = isset( $authordata->ID ) ? $authordata->ID : 0;
283
+ }
284
+
285
+ if ( ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_AUTHOR ] ) && ( is_author() ) ) {
286
+ $dataLayer['pagePostAuthor'] = get_the_author();
287
+ }
288
+ }
289
+
290
+ if ( is_search() ) {
291
+ $dataLayer['siteSearchTerm'] = get_search_query();
292
+ $dataLayer['siteSearchFrom'] = '';
293
+ if ( ! empty( $_SERVER['HTTP_REFERER'] ) ) {
294
+ $referer_url_parts = explode( '?', $_SERVER['HTTP_REFERER'] );
295
+ if ( count( $referer_url_parts ) > 1 ) {
296
+ $dataLayer['siteSearchFrom'] = $referer_url_parts[0] . '?' . rawurlencode( $referer_url_parts[1] );
297
+ } else {
298
+ $dataLayer['siteSearchFrom'] = $referer_url_parts[0];
299
+ }
300
+ }
301
+ $dataLayer['siteSearchResults'] = $wp_query->post_count;
302
+ }
303
+
304
+ if ( is_front_page() && $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTTYPE ] ) {
305
+ $dataLayer['pagePostType'] = 'frontpage';
306
+ }
307
+
308
+ if ( ! is_front_page() && is_home() && $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTTYPE ] ) {
309
+ $dataLayer['pagePostType'] = 'bloghome';
310
+ }
311
+
312
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_BROWSERDATA ] || $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_OSDATA ] || $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_DEVICEDATA ] ) {
313
+ spl_autoload_register(
314
+ function( $class ) {
315
+ $class_parts = explode( '\\', $class );
316
+ if ( 'WhichBrowser' == $class_parts[0] ) {
317
+ include dirname( __FILE__ ) . '/../integration/whichbrowser/' . str_replace( array( 'WhichBrowser', '\\' ), array( 'src', '/' ), $class ) . '.php';
318
+ }
319
+ }
320
+ );
321
+
322
+ require_once dirname( __FILE__ ) . '/../integration/whichbrowser/src/Parser.php';
323
+
324
+ $gtp4wp_headers = getallheaders();
325
+ if ( ( false === $gtp4wp_headers ) && isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
326
+ $gtp4wp_headers = $_SERVER['HTTP_USER_AGENT'];
327
+ }
328
+ if ( false !== $gtp4wp_headers ) {
329
+ $detected = new WhichBrowser\Parser( $gtp4wp_headers );
330
+
331
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_BROWSERDATA ] ) {
332
+ $dataLayer['browserName'] = isset( $detected->browser->name ) ? $detected->browser->name : '';
333
+ $dataLayer['browserVersion'] = isset( $detected->browser->version->value ) ? $detected->browser->version->value : '';
334
+
335
+ $dataLayer['browserEngineName'] = isset( $detected->engine->name ) ? $detected->engine->name : '';
336
+ $dataLayer['browserEngineVersion'] = isset( $detected->engine->version->value ) ? $detected->engine->version->value : '';
337
+ }
338
+
339
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_OSDATA ] ) {
340
+ $dataLayer['osName'] = isset( $detected->os->name ) ? $detected->os->name : '';
341
+ $dataLayer['osVersion'] = isset( $detected->os->version->value ) ? $detected->os->version->value : '';
342
+ }
343
+
344
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_DEVICEDATA ] ) {
345
+ $dataLayer['deviceType'] = isset( $detected->device->type ) ? $detected->device->type : '';
346
+ $dataLayer['deviceManufacturer'] = isset( $detected->device->manufacturer ) ? $detected->device->manufacturer : '';
347
+ $dataLayer['deviceModel'] = isset( $detected->device->model ) ? $detected->device->model : '';
348
+ }
349
+ }
350
+ }
351
+
352
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTCOUNT ] ) {
353
+ $dataLayer['postCountOnPage'] = (int) $wp_query->post_count;
354
+ $dataLayer['postCountTotal'] = (int) $wp_query->found_posts;
355
+ }
356
+
357
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTID ] && is_singular() === true ) {
358
+ $dataLayer['postID'] = (int) get_the_ID();
359
+ }
360
+
361
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_POSTFORMAT ] && is_singular() === true ) {
362
+ $dataLayer['postFormat'] = get_post_format() ?: 'standard';
363
+ }
364
+
365
+ if ( $gtm4wp_options[ GTM4WP_OPTION_BLACKLIST_ENABLE ] > 0 ) {
366
+ $_gtmrestrictlistitems = array();
367
+
368
+ // because of security reasons, we loop through each stored entity in the options and validate them
369
+ // to make sure nobody has entered some 'funny' item manually
370
+ $valid_entity_ids = array_merge(
371
+ array_keys( $gtm4wp_entity_ids[ 'tags' ] ),
372
+ array_keys( $gtm4wp_entity_ids[ 'triggers' ] ),
373
+ array_keys( $gtm4wp_entity_ids[ 'variables' ] )
374
+ );
375
+ foreach( $gtm4wp_options[ GTM4WP_OPTION_BLACKLIST_STATUS ] as $listed_entity ) {
376
+ if ( in_array( $listed_entity, $valid_entity_ids ) ) {
377
+ $_gtmrestrictlistitems[] = $listed_entity;
378
+ }
379
+ }
380
+
381
+ $_gtmwhitelist = array();
382
+ $_gtmblacklist = array();
383
+ if ( $gtm4wp_options[ GTM4WP_OPTION_BLACKLIST_ENABLE ] == 1 ) {
384
+ $_gtmblacklist = array_merge( $_gtmblacklist, $_gtmrestrictlistitems );
385
+ } else {
386
+ $_gtmwhitelist = array_merge( $_gtmwhitelist, $_gtmrestrictlistitems );
387
+ }
388
+
389
+ $dataLayer['gtm.whitelist'] = $_gtmwhitelist;
390
+ $dataLayer['gtm.blacklist'] = $_gtmblacklist;
391
+ }
392
+
393
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_MISCGEOCF ] && isset( $_SERVER['HTTP_CF_IPCOUNTRY'] ) ) {
394
+ $dataLayer['geoCloudflareCountryCode'] = $_SERVER['HTTP_CF_IPCOUNTRY'];
395
+ }
396
+
397
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_WEATHER ] || $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_MISCGEO ] ) {
398
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_WEATHER ] ) {
399
+ $dataLayer['weatherCategory'] = __( '(no weather data available)', 'duracelltomi-google-tag-manager' );
400
+ $dataLayer['weatherDescription'] = __( '(no weather data available)', 'duracelltomi-google-tag-manager' );
401
+ $dataLayer['weatherTemp'] = 0;
402
+ $dataLayer['weatherPressure'] = 0;
403
+ $dataLayer['weatherWindSpeed'] = 0;
404
+ $dataLayer['weatherWindDeg'] = 0;
405
+ $dataLayer['weatherDataStatus'] = 'Initialized with empty data';
406
+ }
407
+
408
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_MISCGEO ] ) {
409
+ $dataLayer['geoCountryCode'] = __( '(no geo data available)', 'duracelltomi-google-tag-manager' );
410
+ $dataLayer['geoCountryName'] = __( '(no geo data available)', 'duracelltomi-google-tag-manager' );
411
+ $dataLayer['geoRegionCode'] = __( '(no geo data available)', 'duracelltomi-google-tag-manager' );
412
+ $dataLayer['geoRegionName'] = __( '(no geo data available)', 'duracelltomi-google-tag-manager' );
413
+ $dataLayer['geoCity'] = __( '(no geo data available)', 'duracelltomi-google-tag-manager' );
414
+ $dataLayer['geoZipcode'] = __( '(no geo data available)', 'duracelltomi-google-tag-manager' );
415
+ $dataLayer['geoLatitude'] = __( '(no geo data available)', 'duracelltomi-google-tag-manager' );
416
+ $dataLayer['geoLongitude'] = __( '(no geo data available)', 'duracelltomi-google-tag-manager' );
417
+ }
418
+
419
+ $client_ip = gtm4wp_get_user_ip();
420
+
421
+ if ( '' !== $client_ip ) {
422
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_WEATHER ] ) {
423
+ $weatherdata = get_transient( 'gtm4wp-weatherdata-' . esc_attr( $client_ip ) );
424
+
425
+ if ( false !== $weatherdata ) {
426
+ $dataLayer['weatherCategory'] = $weatherdata->weather[0]->main;
427
+ $dataLayer['weatherDescription'] = $weatherdata->weather[0]->description;
428
+ $dataLayer['weatherTemp'] = $weatherdata->main->temp;
429
+ $dataLayer['weatherPressure'] = $weatherdata->main->pressure;
430
+ $dataLayer['weatherWindSpeed'] = $weatherdata->wind->speed;
431
+ $dataLayer['weatherWindDeg'] = ( isset($weatherdata->wind->deg) ? $weatherdata->wind->deg : '' );
432
+ $dataLayer['weatherFullWeatherData'] = $weatherdata;
433
+ $dataLayer['weatherDataStatus'] = 'Read from cache';
434
+ } else {
435
+ $dataLayer['weatherDataStatus'] = 'No weather data in cache (' . esc_attr( $client_ip ) . ')';
436
+ }
437
+ }
438
+
439
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_MISCGEO ] ) {
440
+ $geodata = get_transient( 'gtm4wp-geodata-' . esc_attr( $client_ip ) );
441
+
442
+ if ( false !== $geodata ) {
443
+ $dataLayer['geoFullGeoData'] = $geodata;
444
+
445
+ if ( isset( $geodata->latitude ) ) {
446
+ $dataLayer['geoCountryCode'] = $geodata->country_code;
447
+ $dataLayer['geoCountryName'] = $geodata->country_name;
448
+ $dataLayer['geoRegionCode'] = $geodata->region_code;
449
+ $dataLayer['geoRegionName'] = $geodata->region_name;
450
+ $dataLayer['geoCity'] = $geodata->city;
451
+ $dataLayer['geoZipcode'] = $geodata->zip;
452
+ $dataLayer['geoLatitude'] = $geodata->latitude;
453
+ $dataLayer['geoLongitude'] = $geodata->longitude;
454
+ }
455
+ }
456
+ }
457
+ }
458
+ }
459
+
460
+ return $dataLayer;
461
+ }
462
+
463
+ function gtm4wp_wp_loaded() {
464
+ global $gtm4wp_options;
465
+
466
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_WEATHER ] || $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_MISCGEO ] ) {
467
+ $client_ip = gtm4wp_get_user_ip();
468
+ $geodata = get_transient( 'gtm4wp-geodata-' . esc_attr( $client_ip ) );
469
+
470
+ if ( false === $geodata ) {
471
+ $gtm4wp_geodata = @wp_remote_get( sprintf( 'http://api.ipstack.com/%s?access_key=%s&format=1', urlencode( $client_ip ), $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_MISCGEOAPI ] ) );
472
+
473
+ if ( is_array( $gtm4wp_geodata ) && ( 200 == $gtm4wp_geodata['response']['code'] ) ) {
474
+ $gtm4wp_geodata = @json_decode( $gtm4wp_geodata['body'] );
475
+
476
+ if ( is_object( $gtm4wp_geodata ) ) {
477
+ set_transient( 'gtm4wp-geodata-' . esc_attr( $client_ip ), $gtm4wp_geodata, 60 * 60 );
478
+
479
+ $weatherdata = get_transient( 'gtm4wp-weatherdata-' . esc_attr( $client_ip ) );
480
+ if ( false === $weatherdata && isset( $gtm4wp_geodata->latitude ) ) {
481
+
482
+ $weatherdata = wp_remote_get( 'http://api.openweathermap.org/data/2.5/weather?appid=' . $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_WEATHEROWMAPI ] . '&lat=' . $gtm4wp_geodata->latitude . '&lon=' . $gtm4wp_geodata->longitude . '&units=' . ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_WEATHERUNITS ] == 0 ? 'metric' : 'imperial' ) );
483
+
484
+ if ( is_array( $weatherdata ) && ( 200 == $weatherdata['response']['code'] ) ) {
485
+ $weatherdata = @json_decode( $weatherdata['body'] );
486
+
487
+ if ( is_object( $weatherdata ) ) {
488
+ set_transient( 'gtm4wp-weatherdata-' . esc_attr( $client_ip ), $weatherdata, 60 * 60 );
489
+ setcookie( 'gtm4wp_last_weatherstatus', 'Weather data loaded.', 0, "/", "", false, true );
490
+ } else {
491
+ setcookie( 'gtm4wp_last_weatherstatus', 'Openweathermap.org did not return processable data: ' . var_export( $weatherdata, true ), 0, "/", "", false, true );
492
+ }
493
+ } else {
494
+ if ( is_wp_error( $weatherdata ) ) {
495
+ setcookie( 'gtm4wp_last_weatherstatus', 'Openweathermap.org request error: ' . $weatherdata->get_error_message(), 0, "/", "", false, true );
496
+ } else {
497
+ setcookie( 'gtm4wp_last_weatherstatus', 'Openweathermap.org returned status code: ' . $weatherdata['response']['code'], 0, "/", "", false, true );
498
+ }
499
+ }
500
+ }
501
+ } else {
502
+ setcookie( 'gtm4wp_last_weatherstatus', 'ipstack.com did not return lat-lng data: ' . var_export( $gtm4wp_geodata, true ), 0, "/", "", false, true );
503
+ }
504
+ } else {
505
+ if ( is_wp_error( $gtm4wp_geodata ) ) {
506
+ setcookie( 'gtm4wp_last_weatherstatus', 'ipstack.com request error: ' . $gtm4wp_geodata->get_error_message(), 0, "/", "", false, true );
507
+ } else {
508
+ setcookie( 'gtm4wp_last_weatherstatus', 'ipstack.com returned status code: ' . $gtm4wp_geodata['response']['code'], 0, "/", "", false, true );
509
+ }
510
+ }
511
+ }
512
+ }
513
+ }
514
+
515
+ function gtm4wp_get_the_gtm_tag() {
516
+ global $gtm4wp_options, $gtm4wp_datalayer_name, $gtm4wp_container_code_written;
517
+
518
+ $_gtm_tag = '
519
+ <!-- Google Tag Manager (noscript) -->';
520
+
521
+ if ( GTM4WP_PLACEMENT_OFF == $gtm4wp_options[ GTM4WP_OPTION_GTM_PLACEMENT ] ) {
522
+ $gtm4wp_container_code_written = true;
523
+ }
524
+
525
+ if ( ( $gtm4wp_options[ GTM4WP_OPTION_GTM_CODE ] != '' ) && ( ! $gtm4wp_container_code_written ) ) {
526
+ $_gtm_codes = explode( ',', str_replace( array( ';', ' ' ), array( ',', '' ), $gtm4wp_options[ GTM4WP_OPTION_GTM_CODE ] ) );
527
+
528
+ if ( ( '' != $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_AUTH ] ) && ( '' != $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_PREVIEW ] ) ) {
529
+ $_gtm_env = '&gtm_auth=' . $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_AUTH ] . '&gtm_preview=' . $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_PREVIEW ] . '&gtm_cookies_win=x';
530
+ } else {
531
+ $_gtm_env = '';
532
+ }
533
+
534
+ $_gtm_domain_name = 'www.googletagmanager.com';
535
+ if ( $gtm4wp_options[ GTM4WP_OPTION_GTMDOMAIN ] != '' ) {
536
+ $_gtm_domain_name = $gtm4wp_options[ GTM4WP_OPTION_GTMDOMAIN ];
537
+ }
538
+
539
+ foreach ( $_gtm_codes as $one_gtm_code ) {
540
+ $_gtm_tag .= '
541
+ <noscript><iframe src="https://' . $_gtm_domain_name . '/ns.html?id=' . $one_gtm_code . $_gtm_env . '"
542
+ height="0" width="0" style="display:none;visibility:hidden" aria-hidden="true"></iframe></noscript>';
543
+ }
544
+
545
+ $_gtm_tag .= '
546
+ <!-- End Google Tag Manager (noscript) -->';
547
+
548
+ $_gtm_tag = apply_filters( GTM4WP_WPFILTER_GETTHEGTMTAG, $_gtm_tag );
549
+ $gtm4wp_container_code_written = true;
550
+ }
551
+
552
+ return $_gtm_tag;
553
+ }
554
+
555
+ function gtm4wp_the_gtm_tag() {
556
+ echo gtm4wp_get_the_gtm_tag();
557
+ }
558
+
559
+ function gtm4wp_enqueue_scripts() {
560
+ global $gtm4wp_options, $gtp4wp_plugin_url;
561
+
562
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WPCF7 ] ) {
563
+ $in_footer = apply_filters( 'gtm4wp_' . GTM4WP_OPTION_INTEGRATE_WPCF7, true );
564
+ wp_enqueue_script( 'gtm4wp-contact-form-7-tracker', $gtp4wp_plugin_url . 'js/gtm4wp-contact-form-7-tracker.js', array(), GTM4WP_VERSION, $in_footer );
565
+ }
566
+
567
+ if ( $gtm4wp_options[ GTM4WP_OPTION_EVENTS_FORMMOVE ] ) {
568
+ $in_footer = apply_filters( 'gtm4wp_' . GTM4WP_OPTION_EVENTS_FORMMOVE, true );
569
+ wp_enqueue_script( 'gtm4wp-form-move-tracker', $gtp4wp_plugin_url . 'js/gtm4wp-form-move-tracker.js', array(), GTM4WP_VERSION, $in_footer );
570
+ }
571
+
572
+ if ( $gtm4wp_options[ GTM4WP_OPTION_EVENTS_YOUTUBE ] ) {
573
+ require_once dirname( __FILE__ ) . '/../integration/youtube.php';
574
+ }
575
+
576
+ if ( $gtm4wp_options[ GTM4WP_OPTION_EVENTS_VIMEO ] ) {
577
+ require_once dirname( __FILE__ ) . '/../integration/vimeo.php';
578
+ }
579
+
580
+ if ( $gtm4wp_options[ GTM4WP_OPTION_EVENTS_SOUNDCLOUD ] ) {
581
+ require_once dirname( __FILE__ ) . '/../integration/soundcloud.php';
582
+ }
583
+
584
+ if ( $gtm4wp_options[ GTM4WP_OPTION_SCROLLER_ENABLED ] ) {
585
+ $in_footer = apply_filters( 'gtm4wp_' . GTM4WP_OPTION_SCROLLER_ENABLED, false );
586
+ wp_enqueue_script( 'gtm4wp-scroll-tracking', $gtp4wp_plugin_url . 'js/analytics-talk-content-tracking.js', array( 'jquery' ), GTM4WP_VERSION, $in_footer );
587
+ }
588
+ }
589
+
590
+ function gtm4wp_wp_footer() {
591
+ global $gtm4wp_options, $gtm4wp_datalayer_name;
592
+
593
+ if ( GTM4WP_PLACEMENT_FOOTER == $gtm4wp_options[ GTM4WP_OPTION_GTM_PLACEMENT ] ) {
594
+ gtm4wp_the_gtm_tag();
595
+ }
596
+
597
+ $has_html5_support = current_theme_supports( 'html5' );
598
+
599
+ if ( $gtm4wp_options[ GTM4WP_OPTION_EVENTS_NEWUSERREG ] ) {
600
+ $user_logged_in = array_key_exists( "gtm4wp_user_logged_in", $_COOKIE ) ?
601
+ filter_var( $_COOKIE[ "gtm4wp_user_logged_in" ], FILTER_VALIDATE_INT )
602
+ : 0;
603
+
604
+ if ( $user_logged_in ) {
605
+ echo "
606
+ <script" . ( $has_html5_support ? '' : ' type="text/javascript"' ) . ">
607
+ if ( window." . $gtm4wp_datalayer_name . " ) {
608
+ window." . $gtm4wp_datalayer_name . ".push({
609
+ 'event': 'gtm4wp.userLoggedIn'
610
+ });
611
+ }
612
+ </script>";
613
+
614
+ unset( $_COOKIE[ "gtm4wp_user_logged_in" ] );
615
+ }
616
+ }
617
+
618
+ if ( $gtm4wp_options[ GTM4WP_OPTION_EVENTS_USERLOGIN ] ) {
619
+ $user_registered = array_key_exists( "gtm4wp_user_registered", $_COOKIE ) ?
620
+ filter_var( $_COOKIE[ "gtm4wp_user_registered" ], FILTER_VALIDATE_INT )
621
+ : 0;
622
+
623
+ if ( $user_registered ) {
624
+ echo "
625
+ <script" . ( $has_html5_support ? '' : ' type="text/javascript"' ) . ">
626
+ if ( window." . $gtm4wp_datalayer_name . " ) {
627
+ window." . $gtm4wp_datalayer_name . ".push({
628
+ 'event': 'gtm4wp.userRegistered'
629
+ });
630
+ }
631
+ </script>";
632
+
633
+ unset( $_COOKIE[ "gtm4wp_user_registered" ] );
634
+ }
635
+ }
636
+ }
637
+
638
+ function gtm4wp_wp_body_open() {
639
+ global $gtm4wp_options;
640
+
641
+ if ( ( GTM4WP_PLACEMENT_BODYOPEN == $gtm4wp_options[ GTM4WP_OPTION_GTM_PLACEMENT ] ) || ( GTM4WP_PLACEMENT_BODYOPEN_AUTO == $gtm4wp_options[ GTM4WP_OPTION_GTM_PLACEMENT ] ) ) {
642
+ gtm4wp_the_gtm_tag();
643
+ }
644
+ }
645
+
646
+ function gtm4wp_filter_visitor_keys( $dataLayer ) {
647
+ foreach ( $dataLayer as $dl_key => $dl_value ) {
648
+ if ( strpos( $dl_key, 'visitor' ) !== false ) {
649
+ unset( $dataLayer[ $dl_key ] );
650
+ }
651
+ }
652
+
653
+ return $dataLayer;
654
+ }
655
+
656
+ /**
657
+ * GTM4WP global JS variables WordPress filter
658
+ *
659
+ * @author Vincent Koc <https://github.com/koconder/>
660
+ * @link https://github.com/duracelltomi/gtm4wp/issues/34
661
+ * @return mixed returns the
662
+ */
663
+ function gtm4wp_add_global_vars( $vars, $return = false ) {
664
+ if ( ! $return ) {
665
+ if ( function_exists( $vars ) ) {
666
+ $vars = $vars();
667
+ }
668
+ $GLOBALS['gtm4wp_datalayer_globalvars'] = $GLOBALS['gtm4wp_datalayer_globalvars'] . ' ' . $vars;
669
+ }
670
+ return $GLOBALS['gtm4wp_datalayer_globalvars'];
671
+ }
672
+
673
+ function gtm4wp_wp_header_top( $echo = true ) {
674
+ global $gtm4wp_options, $gtm4wp_datalayer_name;
675
+
676
+ $has_html5_support = current_theme_supports( 'html5' );
677
+
678
+ $_gtm_top_content = '
679
+ <!-- Google Tag Manager for WordPress by gtm4wp.com -->
680
+ <script data-cfasync="false" data-pagespeed-no-defer' . ( $has_html5_support ? ' type="text/javascript"' : '' ) . '>//<![CDATA[
681
+ var gtm4wp_datalayer_name = "' . $gtm4wp_datalayer_name . '";
682
+ var ' . $gtm4wp_datalayer_name . ' = ' . $gtm4wp_datalayer_name . ' || [];';
683
+
684
+ // Load in the global variables from gtm4wp_add_global_vars / GTM4WP_WPFILTER_ADDGLOBALVARS filter
685
+ $_gtm_top_content .= apply_filters( GTM4WP_WPFILTER_ADDGLOBALVARS, '' );
686
+
687
+ if ( $gtm4wp_options[ GTM4WP_OPTION_SCROLLER_ENABLED ] ) {
688
+ $_gtm_top_content .= '
689
+
690
+ var gtm4wp_scrollerscript_debugmode = ' . ( $gtm4wp_options[ GTM4WP_OPTION_SCROLLER_DEBUGMODE ] ? 'true' : 'false' ) . ';
691
+ var gtm4wp_scrollerscript_callbacktime = ' . (int) $gtm4wp_options[ GTM4WP_OPTION_SCROLLER_CALLBACKTIME ] . ';
692
+ var gtm4wp_scrollerscript_readerlocation = ' . (int) $gtm4wp_options[ GTM4WP_OPTION_SCROLLER_DISTANCE ] . ';
693
+ var gtm4wp_scrollerscript_contentelementid = "' . $gtm4wp_options[ GTM4WP_OPTION_SCROLLER_CONTENTID ] . '";
694
+ var gtm4wp_scrollerscript_scannertime = ' . (int) $gtm4wp_options[ GTM4WP_OPTION_SCROLLER_READERTIME ] . ';';
695
+ }
696
+
697
+ $_gtm_top_content .= '
698
+ //]]>
699
+ </script>
700
+ <!-- End Google Tag Manager for WordPress by gtm4wp.com -->';
701
+
702
+ if ( ! gtm4wp_amp_running() ) {
703
+ if ( $echo ) {
704
+ echo $_gtm_top_content;
705
+ } else {
706
+ return $_gtm_top_content;
707
+ }
708
+ }
709
+ }
710
+
711
+ function gtm4wp_wp_header_begin( $echo = true ) {
712
+ global $gtm4wp_datalayer_name, $gtm4wp_datalayer_json, $gtm4wp_options, $woocommerce;
713
+
714
+ $has_html5_support = current_theme_supports( 'html5' );
715
+
716
+ $_gtm_header_content = '
717
+ <!-- Google Tag Manager for WordPress by gtm4wp.com -->
718
+ <script data-cfasync="false" data-pagespeed-no-defer' . ( $has_html5_support ? ' type="text/javascript"' : '' ) . '>//<![CDATA[';
719
+
720
+ if ( $gtm4wp_options[ GTM4WP_OPTION_GTM_CODE ] != '' ) {
721
+ $gtm4wp_datalayer_data = array();
722
+ $gtm4wp_datalayer_data = (array) apply_filters( GTM4WP_WPFILTER_COMPILE_DATALAYER, $gtm4wp_datalayer_data );
723
+
724
+ if ( $gtm4wp_options[ GTM4WP_OPTION_INCLUDE_REMARKETING ] ) {
725
+ // add Google Ads remarketing tags as suggested here:
726
+ // https://support.google.com/tagmanager/answer/3002580?hl=en
727
+ add_filter( GTM4WP_WPFILTER_COMPILE_REMARKTING, 'gtm4wp_filter_visitor_keys' );
728
+ $gtm4wp_remarketing_tags = (array) apply_filters( GTM4WP_WPFILTER_COMPILE_REMARKTING, $gtm4wp_datalayer_data );
729
+
730
+ $_gtm_header_content .= "\nvar google_tag_params = ";
731
+ $_gtm_header_content .= json_encode( $gtm4wp_remarketing_tags );
732
+ $_gtm_header_content .= ';';
733
+ $gtm4wp_datalayer_data['google_tag_params'] = '-~-window.google_tag_params-~-';
734
+ }
735
+
736
+ if ( version_compare( PHP_VERSION, '5.4.0' ) >= 0 ) {
737
+ $gtm4wp_datalayer_json = json_encode( $gtm4wp_datalayer_data, JSON_UNESCAPED_UNICODE );
738
+ } else {
739
+ $gtm4wp_datalayer_json = json_encode( $gtm4wp_datalayer_data );
740
+ }
741
+
742
+ // Clean up and then push datalayer to AMP
743
+ $gtm4wp_datalayer_json = str_replace(
744
+ array( '"-~-', '-~-"' ),
745
+ array( '', '' ),
746
+ str_replace( '–', '-', $gtm4wp_datalayer_json )
747
+ );
748
+
749
+ $_gtm_header_content .= '
750
+ var dataLayer_content = ' . $gtm4wp_datalayer_json . ';';
751
+
752
+ // fire WooCommerce order double tracking protection only if WooCommerce is active and user is on the order received page
753
+ if ( isset( $gtm4wp_options ) && ( $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKCLASSICEC ] || $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ] ) && isset( $woocommerce ) && is_order_received_page() ) {
754
+
755
+ $_gtm_header_content .= '
756
+ // if dataLayer contains ecommerce purchase data, check whether it has been already tracked
757
+ if ( dataLayer_content.transactionId || ( dataLayer_content.ecommerce && dataLayer_content.ecommerce.purchase ) ) {
758
+ // read order id already tracked from cookies
759
+ var gtm4wp_orderid_tracked = "";
760
+
761
+ if ( !window.localStorage ) {
762
+ var gtm4wp_cookie = "; " + document.cookie;
763
+ var gtm4wp_cookie_parts = gtm4wp_cookie.split( "; gtm4wp_orderid_tracked=" );
764
+ if ( gtm4wp_cookie_parts.length == 2 ) {
765
+ gtm4wp_orderid_tracked = gtm4wp_cookie_parts.pop().split(";").shift();
766
+ }
767
+ } else {
768
+ gtm4wp_orderid_tracked = window.localStorage.getItem( "gtm4wp_orderid_tracked" );
769
+ }
770
+
771
+ // check enhanced ecommerce
772
+ if ( dataLayer_content.ecommerce && dataLayer_content.ecommerce.purchase ) {
773
+ if ( gtm4wp_orderid_tracked && ( dataLayer_content.ecommerce.purchase.actionField.id == gtm4wp_orderid_tracked ) ) {
774
+ delete dataLayer_content.ecommerce.purchase;
775
+ } else {
776
+ gtm4wp_orderid_tracked = dataLayer_content.ecommerce.purchase.actionField.id;
777
+ }
778
+ }
779
+
780
+ // check app+web ecommerce
781
+ if ( dataLayer_content.ecommerce && dataLayer_content.ecommerce.items ) {
782
+ if ( gtm4wp_orderid_tracked && ( dataLayer_content.ecommerce.transaction_id == gtm4wp_orderid_tracked ) ) {
783
+ delete dataLayer_content.ecommerce.affiliation;
784
+ delete dataLayer_content.ecommerce.value;
785
+ delete dataLayer_content.ecommerce.currency;
786
+ delete dataLayer_content.ecommerce.tax;
787
+ delete dataLayer_content.ecommerce.shipping;
788
+ delete dataLayer_content.ecommerce.transaction_id;
789
+
790
+ delete dataLayer_content.ecommerce.items;
791
+ } else {
792
+ gtm4wp_orderid_tracked = dataLayer_content.ecommerce.purchase.actionField.id;
793
+ }
794
+ }
795
+
796
+ // check standard ecommerce
797
+ if ( dataLayer_content.transactionId ) {
798
+ if ( gtm4wp_orderid_tracked && ( dataLayer_content.transactionId == gtm4wp_orderid_tracked ) ) {
799
+ delete dataLayer_content.transactionId;
800
+ delete dataLayer_content.transactionDate;
801
+ delete dataLayer_content.transactionType;
802
+ delete dataLayer_content.transactionAffiliation;
803
+ delete dataLayer_content.transactionTotal;
804
+ delete dataLayer_content.transactionShipping;
805
+ delete dataLayer_content.transactionTax;
806
+ delete dataLayer_content.transactionPaymentType;
807
+ delete dataLayer_content.transactionCurrency;
808
+ delete dataLayer_content.transactionShippingMethod;
809
+ delete dataLayer_content.transactionPromoCode;
810
+ delete dataLayer_content.transactionProducts;
811
+ } else {
812
+ gtm4wp_orderid_tracked = dataLayer_content.transactionId;
813
+ }
814
+ }
815
+
816
+ if ( gtm4wp_orderid_tracked ) {
817
+ if ( !window.localStorage ) {
818
+ var gtm4wp_orderid_cookie_expire = new Date();
819
+ gtm4wp_orderid_cookie_expire.setTime( gtm4wp_orderid_cookie_expire.getTime() + (365*24*60*60*1000) );
820
+ var gtm4wp_orderid_cookie_expires_part = "expires=" + gtm4wp_orderid_cookie_expire.toUTCString();
821
+ document.cookie = "gtm4wp_orderid_tracked=" + gtm4wp_orderid_tracked + ";" + gtm4wp_orderid_cookie_expires_part + ";path=/";
822
+ } else {
823
+ window.localStorage.setItem( "gtm4wp_orderid_tracked", gtm4wp_orderid_tracked );
824
+ }
825
+ }
826
+
827
+ }';
828
+ }
829
+
830
+ $_gtm_header_content .= '
831
+ ' . $gtm4wp_datalayer_name . '.push( dataLayer_content );';
832
+ }
833
+
834
+ $_gtm_header_content .= '//]]>
835
+ </script>';
836
+
837
+ $_gtm_header_content .= apply_filters( GTM4WP_WPFILTER_AFTER_DATALAYER, '' );
838
+
839
+ if ( ( $gtm4wp_options[ GTM4WP_OPTION_GTM_CODE ] != '' ) && ( GTM4WP_PLACEMENT_OFF != $gtm4wp_options[ GTM4WP_OPTION_GTM_PLACEMENT ] ) ) {
840
+ $_gtm_codes = explode( ',', str_replace( array( ';', ' ' ), array( ',', '' ), $gtm4wp_options[ GTM4WP_OPTION_GTM_CODE ] ) );
841
+ $add_cookiebot_ignore = $gtm4wp_options[ GTM4WP_OPTION_INTEGRATE_COOKIEBOT ];
842
+
843
+ $_gtm_tag = '';
844
+ foreach ( $_gtm_codes as $one_gtm_code ) {
845
+ if ( ( '' != $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_AUTH ] ) && ( '' != $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_PREVIEW ] ) ) {
846
+ $_gtm_env = "+'&gtm_auth=" . $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_AUTH ] . '&gtm_preview=' . $gtm4wp_options[ GTM4WP_OPTION_ENV_GTM_PREVIEW ] . "&gtm_cookies_win=x'";
847
+ } else {
848
+ $_gtm_env = '';
849
+ }
850
+
851
+ $_gtm_domain_name = 'www.googletagmanager.com';
852
+ if ( $gtm4wp_options[ GTM4WP_OPTION_GTMDOMAIN ] != '' ) {
853
+ $_gtm_domain_name = $gtm4wp_options[ GTM4WP_OPTION_GTMDOMAIN ];
854
+ }
855
+
856
+ $_gtm_tag .= '
857
+ <script data-cfasync="false"' . ( $add_cookiebot_ignore ? ' data-cookieconsent="ignore"' : '' ) . '>//<![CDATA[
858
+ (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({\'gtm.start\':
859
+ new Date().getTime(),event:\'gtm.js\'});var f=d.getElementsByTagName(s)[0],
860
+ j=d.createElement(s),dl=l!=\'dataLayer\'?\'&l=\'+l:\'\';j.async=true;j.src=
861
+ \'//' . $_gtm_domain_name . '/gtm.\'' . '+\'js?id=\'+i+dl' . $_gtm_env . ';f.parentNode.insertBefore(j,f);
862
+ })(window,document,\'script\',\'' . $gtm4wp_datalayer_name . '\',\'' . $one_gtm_code . '\');//]]>
863
+ </script>';
864
+ }
865
+
866
+ $_gtm_tag .= '
867
+ <!-- End Google Tag Manager -->';
868
+
869
+ $_gtm_tag = apply_filters( GTM4WP_WPFILTER_GETTHEGTMTAG, $_gtm_tag );
870
+ $_gtm_header_content .= $_gtm_tag;
871
+ }
872
+
873
+ $_gtm_header_content .= '
874
+ <!-- End Google Tag Manager for WordPress by gtm4wp.com -->';
875
+
876
+ if ( ! gtm4wp_amp_running() ) {
877
+ if ( $echo ) {
878
+ echo $_gtm_header_content;
879
+ } else {
880
+ return $_gtm_header_content;
881
+ }
882
+ }
883
+ }
884
+
885
+ function gtm4wp_wp_login() {
886
+ setcookie(
887
+ "gtm4wp_user_logged_in",
888
+ "1",
889
+ 0,
890
+ "/",
891
+ "",
892
+ (false !== strstr( get_option( 'home' ), 'https:' )) && is_ssl(),
893
+ true
894
+ );
895
+ }
896
+
897
+ function gtm4wp_user_register() {
898
+ setcookie(
899
+ "gtm4wp_user_registered",
900
+ "1",
901
+ 0,
902
+ "/",
903
+ "",
904
+ (false !== strstr( get_option( 'home' ), 'https:' )) && is_ssl(),
905
+ true
906
+ );
907
+ }
908
+
909
+ function gtm4wp_rocket_excluded_inline_js_content( $pattern ) {
910
+ $pattern[] = 'dataLayer';
911
+ $pattern[] = 'gtm4wp';
912
+
913
+ return $pattern;
914
+ }
915
+
916
+ function gtm4wp_wp_init() {
917
+ if ( array_key_exists( "gtm4wp_user_logged_in", $_COOKIE ) ) {
918
+ setcookie(
919
+ "gtm4wp_user_logged_in",
920
+ "",
921
+ -10000,
922
+ "/",
923
+ "",
924
+ (false !== strstr( get_option( 'home' ), 'https:' )) && is_ssl(),
925
+ true
926
+ );
927
+ }
928
+
929
+ if ( array_key_exists( "gtm4wp_user_registered", $_COOKIE ) ) {
930
+ setcookie(
931
+ "gtm4wp_user_registered",
932
+ "",
933
+ -10000,
934
+ "/",
935
+ "",
936
+ (false !== strstr( get_option( 'home' ), 'https:' )) && is_ssl(),
937
+ true
938
+ );
939
+ }
940
+ }
941
+
942
+ add_action( 'wp_enqueue_scripts', 'gtm4wp_enqueue_scripts' );
943
+ $gtm4wp_header_begin_prior = 10;
944
+ if ( isset( $GLOBALS['gtm4wp_options'] ) && $GLOBALS['gtm4wp_options'][ GTM4WP_OPTION_LOADEARLY ] ) {
945
+ $gtm4wp_header_begin_prior = 2;
946
+ }
947
+ add_action( 'wp_head', 'gtm4wp_wp_header_begin', $gtm4wp_header_begin_prior, 0 );
948
+ add_action( 'wp_head', 'gtm4wp_wp_header_top', 1, 0 );
949
+ add_action( 'wp_footer', 'gtm4wp_wp_footer' );
950
+ add_action( 'wp_loaded', 'gtm4wp_wp_loaded' );
951
+ add_filter( GTM4WP_WPFILTER_COMPILE_DATALAYER, 'gtm4wp_add_basic_datalayer_data' );
952
+ add_action( 'init', 'gtm4wp_wp_init' );
953
+
954
+ // to be able to easily migrate from other Google Tag Manager plugins
955
+ add_action( 'body_open', 'gtm4wp_wp_body_open' );
956
+
957
+ // compatibility with existing themes that natively support code injection after opening body tag
958
+ add_action( 'genesis_before', 'gtm4wp_wp_body_open' ); // Genisis theme
959
+ add_action( 'generate_before_header', 'gtm4wp_wp_body_open', 0 ); // GeneratePress theme
960
+ add_action( 'elementor/page_templates/canvas/before_content', 'gtm4wp_wp_body_open' ); // Elementor
961
+ add_action( 'ct_before_builder', 'gtm4wp_wp_body_open', 0 ); // Oxygen Builder
962
+ add_action( 'fl_before_builder', 'gtm4wp_wp_body_open', 0 ); // Beaver Builder Theme
963
+
964
+ // standard WP theme support for body open tags
965
+ add_action( 'wp_body_open', 'gtm4wp_wp_body_open' );
966
+
967
+ add_filter( 'rocket_excluded_inline_js_content', 'gtm4wp_rocket_excluded_inline_js_content' ); // WP Rocket
968
+ if (
969
+ isset( $GLOBALS['gtm4wp_options'] )
970
+ && (
971
+ $GLOBALS['gtm4wp_options'][ GTM4WP_OPTION_INTEGRATE_WCTRACKCLASSICEC ]
972
+ || $GLOBALS['gtm4wp_options'][ GTM4WP_OPTION_INTEGRATE_WCTRACKENHANCEDEC ]
973
+ )
974
+ && isset( $GLOBALS['woocommerce'] )
975
+ && version_compare( WC()->version, '3.2', '>=' ) // only activate WooCommerce integration for minimum supported WooCommerce version
976
+ ) {
977
+ require_once dirname( __FILE__ ) . '/../integration/woocommerce.php';
978
+ }
979
+
980
+ if ( isset( $GLOBALS['gtm4wp_options'] ) && ( $GLOBALS['gtm4wp_options'][ GTM4WP_OPTION_INTEGRATE_GOOGLEOPTIMIZEIDS ] != '' ) ) {
981
+ require_once dirname( __FILE__ ) . '/../integration/google-optimize.php';
982
+ }
983
+
984
+ if ( isset( $GLOBALS['gtm4wp_options'] ) && ( $GLOBALS['gtm4wp_options'][ GTM4WP_OPTION_EVENTS_USERLOGIN ] ) ) {
985
+ add_action( 'wp_login', 'gtm4wp_wp_login' );
986
+ }
987
+
988
+ if ( isset( $GLOBALS['gtm4wp_options'] ) && ( $GLOBALS['gtm4wp_options'][ GTM4WP_OPTION_EVENTS_NEWUSERREG ] ) ) {
989
+ add_action( 'user_register', 'gtm4wp_user_register' );
990
+ }
readme.txt CHANGED
@@ -4,8 +4,8 @@ Donate link: https://gtm4wp.com/
4
  Tags: google tag manager, tag manager, gtm, google, adwords, google adwords, google ads, adwords remarketing, google ads remarketing, remarketing, google analytics, analytics, facebook ads, facebook remarketing, facebook pixel, google optimize, personalisation
5
  Requires at least: 3.4.0
6
  Requires PHP: 5.6
7
- Tested up to: 5.7.2
8
- Stable tag: 1.13.1
9
  License: GPLv3
10
  License URI: http://www.gnu.org/licenses/gpl.html
11
 
@@ -233,6 +233,28 @@ https://gtm4wp.com/how-to-articles/how-to-exclude-admin-users-from-being-tracked
233
 
234
  == Changelog ==
235
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
  = 1.13.1 =
237
 
238
  * Fix: better PHP8 compatibility
@@ -716,6 +738,10 @@ Please report all bugs found in my plugin using the [contact form on my website]
716
 
717
  == Upgrade Notice ==
718
 
 
 
 
 
719
  = 1.13.1 =
720
 
721
  Bugfix release
4
  Tags: google tag manager, tag manager, gtm, google, adwords, google adwords, google ads, adwords remarketing, google ads remarketing, remarketing, google analytics, analytics, facebook ads, facebook remarketing, facebook pixel, google optimize, personalisation
5
  Requires at least: 3.4.0
6
  Requires PHP: 5.6
7
+ Tested up to: 5.8.2
8
+ Stable tag: 1.14
9
  License: GPLv3
10
  License URI: http://www.gnu.org/licenses/gpl.html
11
 
233
 
234
  == Changelog ==
235
 
236
+ = 1.14 =
237
+
238
+ * Added: support for tracking WooCommerce Block based product lists, except the "All Products" block
239
+ * Added: support for [new_customer parameter](https://support.google.com/google-ads/answer/9917012?hl=en-AU#zippy=%2Cinstall-with-google-tag-manager) for Google Smart Shopping campaigns
240
+ * Added: SHA256 hashed versions of data layer variables containing email addresses: customerBillingEmailHash on WooCommerce order received pages and visitorEmailHash on generic uses cases
241
+ * Added: WooCommerce - if for some reason is_order_received_page() reports false on the order received page, woocommerce_thankyou hook will be used as backup
242
+ * Updated: removed jQuery dependency from plugin modules: contact form 7 integration, form move tracker, Vimeo, YouTube, Soundcloud, partly WooCommerce
243
+ * Updated: moved the hidden helper span element in products lists to the end of the product box to make more compatible with themes
244
+ * Updated: more consistent retrieval of product categories - by [Dekadinious](https://github.com/Dekadinious)
245
+ * Updated: gtm4wp_product_readded_to_cart cookie replaced with a WooCommerce session variable to use fewer cookies in this plugin
246
+ * Updated: gtm4wp_user_logged_in, gtm4wp_user_registered and gtm4wp_last_weatherstatus cookies are now HTTP only cookies
247
+ * Updated: replaced deprecated jQuery method and event usage in WP admin
248
+ * Updated: added rel="noopener" to links pointing to external sites on WP admin page
249
+ * Updated: Hiding the iframe tag from assistive technologies as it provides no functionality for the end user. This will also alleviate a11y audit warnings.
250
+ * Fixed: proper values for visitorType data layer variable
251
+ * Fixed: replaced unsafe usage of eval() in WooCommerce QuickView plugin integration
252
+ * Fixed: type check of the order ID obtained from a cookie before using the value
253
+ * Fixed: navigation issues in Safari if browser loads previous page from cache. GTM4WP will now force Safari to always reload pages.
254
+ * Fixed: Do not trigger browser change event in WooCommerce checkout page submit event handler. It caused issues with other 3rd party plugins.
255
+ * Fixed: HTML5 detection. - by [Sjoerd](https://github.com/sjoerdkoelewijn)
256
+ * Fixed: Username not included in datalayer if no other user attribute is included - by [StaymanHou](https://github.com/StaymanHou)
257
+
258
  = 1.13.1 =
259
 
260
  * Fix: better PHP8 compatibility
738
 
739
  == Upgrade Notice ==
740
 
741
+ = 1.14 =
742
+
743
+ Initial support for WooCommerce Blocks, removed jQuery usage in JavaScript codes (except for WooCommerce related codes)
744
+
745
  = 1.13.1 =
746
 
747
  Bugfix release