-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwp-referrer-tracker.php
974 lines (877 loc) · 33.9 KB
/
wp-referrer-tracker.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
<?php
/**
* Plugin Name: Referrer Tracker for WP
* Plugin URI: https://github.com/marcalorri/wp-referrer-tracker
* Description: Track and store referrer information in your WordPress forms
* Version: 1.4.2
* Author: Marçal Orri
* Author URI: https://github.com/marcalorri
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: wp-referrer-tracker
* Domain Path: /languages
*/
if (!defined('ABSPATH')) {
exit;
}
class WP_Referrer_Tracker {
private static $instance = null;
private $field_prefix = 'wrt_';
/**
* Get the plugin instance
*
* @return WP_Referrer_Tracker The plugin instance
*/
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Constructor
*
* Initialize the plugin by adding hooks and setting up cookies
*/
private function __construct() {
add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
add_action('init', array($this, 'init'));
// Add settings page
add_action('admin_menu', array($this, 'add_admin_menu'));
add_action('admin_init', array($this, 'register_settings'));
}
/**
* Initialize the plugin
*
* Set up cookies and initialize the plugin
*/
public function init() {
add_action('admin_init', array($this, 'register_settings'));
add_action('admin_menu', array($this, 'add_admin_menu'));
// Insertar el código de tracking
add_action('wp_footer', array($this, 'insert_tracking_code'));
// Si está activada la inserción automática de campos
if (get_option('wrt_settings')['auto_fields']) {
add_filter('wpcf7_form_elements', array($this, 'add_hidden_fields_cf7'));
}
// Initialize tracking
$this->init_tracking();
}
/**
* Añadir campos ocultos a Contact Form 7
*/
public function add_hidden_fields_cf7($elements) {
$prefix = get_option('wrt_settings')['field_prefix'];
$hidden_fields = "
[hidden {$prefix}source class:js-wrt-source \"\"]
[hidden {$prefix}medium class:js-wrt-medium \"\"]
[hidden {$prefix}campaign class:js-wrt-campaign \"\"]
[hidden {$prefix}referrer class:js-wrt-referrer \"\"]
";
return $elements . $hidden_fields;
}
/**
* Insertar el código de tracking
*/
public function insert_tracking_code() {
// Obtener los valores de las cookies de forma segura
$source = $this->get_source();
$medium = $this->get_medium();
$campaign = $this->get_campaign();
$referrer = $this->get_referrer();
?>
<script>
// Valores de referrer
var wrtValues = {
source: <?php echo wp_json_encode($source); ?>,
medium: <?php echo wp_json_encode($medium); ?>,
campaign: <?php echo wp_json_encode($campaign); ?>,
referrer: <?php echo wp_json_encode($referrer); ?>
};
// Función para actualizar campos
function wrtUpdateFields() {
if (window.wrt_debug) {
console.log('WRT: Actualizando campos con valores:', wrtValues);
}
// Actualizar campos por clase
document.querySelectorAll('.js-wrt-source').forEach(function(el) {
el.value = wrtValues.source;
if (window.wrt_debug) {
console.log('WRT: Campo source actualizado:', el.value);
}
});
document.querySelectorAll('.js-wrt-medium').forEach(function(el) {
el.value = wrtValues.medium;
if (window.wrt_debug) {
console.log('WRT: Campo medium actualizado:', el.value);
}
});
document.querySelectorAll('.js-wrt-campaign').forEach(function(el) {
el.value = wrtValues.campaign;
if (window.wrt_debug) {
console.log('WRT: Campo campaign actualizado:', el.value);
}
});
document.querySelectorAll('.js-wrt-referrer').forEach(function(el) {
el.value = wrtValues.referrer;
if (window.wrt_debug) {
console.log('WRT: Campo referrer actualizado:', el.value);
}
});
}
// Actualizar campos cuando el DOM está listo
document.addEventListener('DOMContentLoaded', function() {
if (window.wrt_debug) {
console.log('WRT: DOM cargado, actualizando campos...');
}
wrtUpdateFields();
});
// Actualizar campos antes de enviar el formulario CF7
document.addEventListener('wpcf7submit', function() {
if (window.wrt_debug) {
console.log('WRT: Formulario enviado, actualizando campos...');
}
wrtUpdateFields();
});
</script>
<?php
}
/**
* Add settings page
*
* Add a settings page to the WordPress admin dashboard
*/
public function add_admin_menu() {
add_options_page(
'WP Referrer Tracker Settings',
'Referrer Tracker',
'manage_options',
'wp-referrer-tracker',
array($this, 'display_settings_page')
);
}
/**
* Display the plugin settings page
*/
public function display_settings_page() {
?>
<div class="wrap">
<h1><?php echo esc_html(get_admin_page_title()); ?></h1>
<?php
settings_errors('wp_referrer_tracker');
?>
<form action="options.php" method="post">
<?php
settings_fields('wp_referrer_tracker');
do_settings_sections('wp-referrer-tracker');
submit_button();
?>
</form>
<?php
$options = get_option('wrt_settings');
$this->display_implementation_instructions($options['form_plugin']);
?>
</div>
<?php
}
/**
* Display implementation instructions based on selected form plugin
*/
private function display_implementation_instructions($plugin) {
echo '<div class="wrt-instructions" style="margin-top: 20px; padding: 15px; background: #fff; border: 1px solid #ccd0d4; box-shadow: 0 1px 1px rgba(0,0,0,.04);">';
echo '<h2>Implementation Instructions</h2>';
switch ($plugin) {
case 'cf7':
?>
<h3>Contact Form 7 Implementation</h3>
<p>Add these hidden fields to your Contact Form 7 form:</p>
<pre style="background: #f5f5f5; padding: 10px; overflow: auto;">
[hidden wrt_source class:js-wrt-source ""]
[hidden wrt_medium class:js-wrt-medium ""]
[hidden wrt_campaign class:js-wrt-campaign ""]
[hidden wrt_referrer class:js-wrt-referrer ""]</pre>
<p><strong>Important notes:</strong></p>
<ul style="list-style-type: disc; margin-left: 20px;">
<li>The field names must use underscore (e.g., <code>wrt_source</code>)</li>
<li>The classes must use hyphen (e.g., <code>js-wrt-source</code>)</li>
<li>Leave the default value empty (<code>""</code>)</li>
<li>Do not add any additional classes or attributes</li>
</ul>
<?php
break;
case 'wpforms':
?>
<h3>WPForms Implementation</h3>
<p>Add these hidden fields to your WPForms form:</p>
<ol style="list-style-type: decimal; margin-left: 20px;">
<li>Go to your form editor</li>
<li>Drag and drop 4 "Hidden Field" elements from the "Fancy Fields" section</li>
<li>Configure each hidden field:</li>
</ol>
<table class="wp-list-table widefat striped" style="margin-top: 10px;">
<thead>
<tr>
<th>Field Label</th>
<th>Field Name</th>
<th>CSS Classes</th>
</tr>
</thead>
<tbody>
<tr>
<td>Source</td>
<td>wrt_source</td>
<td>js-wrt-source</td>
</tr>
<tr>
<td>Medium</td>
<td>wrt_medium</td>
<td>js-wrt-medium</td>
</tr>
<tr>
<td>Campaign</td>
<td>wrt_campaign</td>
<td>js-wrt-campaign</td>
</tr>
<tr>
<td>Referrer</td>
<td>wrt_referrer</td>
<td>js-wrt-referrer</td>
</tr>
</tbody>
</table>
<?php
break;
case 'gravity':
?>
<h3>Gravity Forms Implementation</h3>
<p>Add these hidden fields to your Gravity Forms form:</p>
<ol style="list-style-type: decimal; margin-left: 20px;">
<li>Go to your form editor</li>
<li>Add 4 "Hidden" fields from the "Advanced Fields" section</li>
<li>Configure each hidden field:</li>
</ol>
<table class="wp-list-table widefat striped" style="margin-top: 10px;">
<thead>
<tr>
<th>Field Label</th>
<th>Field Name</th>
<th>CSS Class Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>Source</td>
<td>wrt_source</td>
<td>js-wrt-source</td>
</tr>
<tr>
<td>Medium</td>
<td>wrt_medium</td>
<td>js-wrt-medium</td>
</tr>
<tr>
<td>Campaign</td>
<td>wrt_campaign</td>
<td>js-wrt-campaign</td>
</tr>
<tr>
<td>Referrer</td>
<td>wrt_referrer</td>
<td>js-wrt-referrer</td>
</tr>
</tbody>
</table>
<p><em>Note: Add the CSS Class Name in the "Advanced" tab of each field.</em></p>
<?php
break;
case 'generic':
?>
<h3>Generic HTML Forms Implementation</h3>
<p>Add these hidden fields to your HTML form:</p>
<pre style="background: #f5f5f5; padding: 10px; overflow: auto;">
<input type="hidden" name="wrt_source" class="js-wrt-source" value="">
<input type="hidden" name="wrt_medium" class="js-wrt-medium" value="">
<input type="hidden" name="wrt_campaign" class="js-wrt-campaign" value="">
<input type="hidden" name="wrt_referrer" class="js-wrt-referrer" value=""></pre>
<p><strong>Important notes:</strong></p>
<ul style="list-style-type: disc; margin-left: 20px;">
<li>The name attributes must use underscore (e.g., <code>wrt_source</code>)</li>
<li>The class attributes must use hyphen (e.g., <code>js-wrt-source</code>)</li>
<li>Leave the value attribute empty (<code>value=""</code>)</li>
</ul>
<?php
break;
default:
echo '<p>Please select a form plugin to see implementation instructions.</p>';
break;
}
echo '</div>';
}
/**
* Register settings
*
* Register the plugin settings and add fields to the settings page
*/
public function register_settings() {
register_setting('wp_referrer_tracker', 'wrt_settings', array(
'type' => 'array',
'default' => array(
'form_plugin' => 'cf7',
'field_prefix' => 'wrt_',
'auto_fields' => false
),
'sanitize_callback' => array($this, 'sanitize_settings')
));
add_settings_section(
'wrt_main_section',
'Main Settings',
array($this, 'section_text'),
'wp-referrer-tracker'
);
add_settings_field(
'form_plugin',
'Form Plugin',
array($this, 'form_plugin_field'),
'wp-referrer-tracker',
'wrt_main_section'
);
add_settings_field(
'field_prefix',
'Field Prefix',
array($this, 'field_prefix_field'),
'wp-referrer-tracker',
'wrt_main_section'
);
add_settings_field(
'auto_fields',
'Auto-insert Hidden Fields',
array($this, 'auto_fields_field'),
'wp-referrer-tracker',
'wrt_main_section'
);
}
/**
* Sanitize settings
*/
public function sanitize_settings($input) {
$sanitized = array();
// Form Plugin
if (isset($input['form_plugin'])) {
$sanitized['form_plugin'] = sanitize_text_field($input['form_plugin']);
}
// Field Prefix
if (isset($input['field_prefix'])) {
$sanitized['field_prefix'] = sanitize_text_field($input['field_prefix']);
}
// Auto Fields
$sanitized['auto_fields'] = isset($input['auto_fields']) ? true : false;
return $sanitized;
}
/**
* Section text
*/
public function section_text() {
echo '<p>Configure your referrer tracking settings here.</p>';
}
/**
* Form plugin field
*/
public function form_plugin_field() {
$options = get_option('wrt_settings');
$current = isset($options['form_plugin']) ? $options['form_plugin'] : 'cf7';
?>
<select name="wrt_settings[form_plugin]">
<option value="cf7" <?php selected($current, 'cf7'); ?>>Contact Form 7</option>
<option value="wpforms" <?php selected($current, 'wpforms'); ?>>WPForms</option>
<option value="gravity" <?php selected($current, 'gravity'); ?>>Gravity Forms</option>
<option value="generic" <?php selected($current, 'generic'); ?>>Generic HTML Forms</option>
</select>
<?php
}
/**
* Field prefix field
*/
public function field_prefix_field() {
$options = get_option('wrt_settings');
$current = isset($options['field_prefix']) ? $options['field_prefix'] : 'wrt_';
?>
<input type="text" name="wrt_settings[field_prefix]" value="<?php echo esc_attr($current); ?>" />
<p class="description">Prefix for the hidden fields (e.g., wrt_)</p>
<?php
}
/**
* Auto fields field
*/
public function auto_fields_field() {
$options = get_option('wrt_settings');
$checked = isset($options['auto_fields']) ? $options['auto_fields'] : false;
?>
<input type="checkbox" name="wrt_settings[auto_fields]" value="1" <?php checked($checked, true); ?> />
<p class="description">Automatically insert hidden fields into Contact Form 7 forms</p>
<?php
}
/**
* Set up cookies
*
* Set up cookies to track referrer information
*/
private function set_cookies() {
// Si ya existen las cookies, no las sobreescribimos
if (isset($_COOKIE['wrt_source']) && !empty($_COOKIE['wrt_source'])) {
$this->debug_log('Las cookies ya existen, no se sobreescriben');
return;
}
$referrer = '';
if (isset($_SERVER['HTTP_REFERER'])) {
$referrer = esc_url_raw(wp_unslash($_SERVER['HTTP_REFERER']));
}
$this->debug_log('Referrer detectado: ' . $referrer);
// Obtener los parámetros UTM de forma segura
$utm_source = '';
$utm_medium = '';
$utm_campaign = '';
// Solo procesar parámetros UTM si el nonce es válido
if ($this->verify_nonce()) {
if (isset($_GET['utm_source'])) {
$utm_source = sanitize_text_field(wp_unslash($_GET['utm_source']));
}
if (isset($_GET['utm_medium'])) {
$utm_medium = sanitize_text_field(wp_unslash($_GET['utm_medium']));
}
if (isset($_GET['utm_campaign'])) {
$utm_campaign = sanitize_text_field(wp_unslash($_GET['utm_campaign']));
}
$this->debug_log('UTM params procesados con nonce válido');
} else {
$this->debug_log('Nonce no válido o no presente, ignorando parámetros UTM');
}
$this->debug_log('UTM params - source: ' . $utm_source . ', medium: ' . $utm_medium . ', campaign: ' . $utm_campaign);
// Si hay parámetros UTM, los usamos
if (!empty($utm_source)) {
$source = $utm_source;
$medium = !empty($utm_medium) ? $utm_medium : 'referral';
$campaign = $utm_campaign;
}
// Si no hay UTM, analizamos el referrer
else if (!empty($referrer)) {
$parsed_url = wp_parse_url($referrer);
$host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
// Google
if (strpos($host, 'google') !== false) {
$source = 'google';
$medium = isset($_GET['gclid']) ? 'cpc' : 'organic';
}
// Facebook
else if (strpos($host, 'facebook') !== false || strpos($host, 'fb') !== false) {
$source = 'facebook';
$medium = 'social';
}
// Otros casos
else {
$source = $host;
$medium = 'referral';
}
$campaign = '';
}
// Si no hay referrer ni UTM
else {
$source = 'direct';
$medium = 'none';
$campaign = '';
}
$this->debug_log('Valores finales - source: ' . $source . ', medium: ' . $medium . ', campaign: ' . $campaign);
// Establecer las cookies con una duración de 30 días
$expire = time() + (30 * 24 * 60 * 60);
$path = '/';
setcookie('wrt_source', $source, $expire, $path);
setcookie('wrt_medium', $medium, $expire, $path);
setcookie('wrt_campaign', $campaign, $expire, $path);
setcookie('wrt_referrer', $referrer, $expire, $path);
$this->debug_log('Cookies establecidas con éxito');
// También guardamos los valores en la sesión actual
$_COOKIE['wrt_source'] = $source;
$_COOKIE['wrt_medium'] = $medium;
$_COOKIE['wrt_campaign'] = $campaign;
$_COOKIE['wrt_referrer'] = $referrer;
}
/**
* Initialize tracking
*
* Set up initial tracking values
*/
public function init_tracking() {
if (!is_admin()) {
$this->set_cookies();
}
}
/**
* Parse referrer information to determine traffic source and medium
*
* This method analyzes the referrer URL and various parameters to determine
* the traffic source (e.g., google, facebook) and medium (e.g., organic, cpc).
* It can differentiate between paid and organic traffic through various indicators.
*
* @param string $referrer The referrer URL to analyze
* @return array Associative array with source, medium, and campaign information
* - source: The traffic source (e.g., google, facebook, direct)
* - medium: The traffic medium (e.g., organic, cpc, social)
* - campaign: The campaign name (from UTM parameters)
*/
private function parse_referrer($referrer) {
$parsed = array(
'source' => 'direct',
'medium' => 'none',
'campaign' => ''
);
if (empty($referrer)) {
return $parsed;
}
// Analizar la URL del referrer
$parsed_referrer = wp_parse_url($referrer);
$referrer_host = isset($parsed_referrer['host']) ? $parsed_referrer['host'] : '';
$parsed_current = wp_parse_url(get_site_url());
$current_host = isset($parsed_current['host']) ? $parsed_current['host'] : '';
$referrer_path = isset($parsed_referrer['path']) ? $parsed_referrer['path'] : '';
$query = isset($parsed_referrer['query']) ? $parsed_referrer['query'] : '';
parse_str($query ?? '', $params);
// Check if it's an internal referrer
if ($referrer_host === $current_host) {
return $parsed;
}
// Check for UTM parameters first
if (!empty($params['utm_source'])) {
$parsed['source'] = sanitize_text_field($params['utm_source']);
$parsed['medium'] = sanitize_text_field($params['utm_medium'] ?? '');
$parsed['campaign'] = sanitize_text_field($params['utm_campaign'] ?? '');
return $parsed;
}
// Check for paid traffic parameters
$paid_parameters = array(
'gclid', // Google Ads
'fbclid', // Facebook Ads
'msclkid', // Microsoft Ads
'dclid', // DoubleClick
'ttclid', // TikTok Ads
'twclid' // Twitter Ads
);
foreach ($paid_parameters as $param) {
if (isset($params[$param])) {
switch ($param) {
case 'gclid':
$parsed['source'] = 'google';
$parsed['medium'] = 'cpc';
break;
case 'fbclid':
$parsed['source'] = 'facebook';
$parsed['medium'] = 'cpc';
break;
case 'msclkid':
$parsed['source'] = 'bing';
$parsed['medium'] = 'cpc';
break;
case 'dclid':
$parsed['source'] = 'doubleclick';
$parsed['medium'] = 'cpc';
break;
case 'ttclid':
$parsed['source'] = 'tiktok';
$parsed['medium'] = 'cpc';
break;
case 'twclid':
$parsed['source'] = 'twitter';
$parsed['medium'] = 'cpc';
break;
}
return $parsed;
}
}
// Search Engines with specific checks for paid traffic
$search_engines = array(
'google' => array(
'domains' => array('google', 'google.com', 'google.es', 'google.co.uk'),
'paid_indicators' => array(
'params' => array('gclid'),
'paths' => array('/aclk', '/pagead'),
'refs' => array('adwords', 'googleads')
)
),
'bing' => array(
'domains' => array('bing', 'bing.com'),
'paid_indicators' => array(
'params' => array('msclkid'),
'paths' => array('/bing/ck.php'),
'refs' => array('msn', 'bingads')
)
),
'yahoo' => array(
'domains' => array('yahoo', 'yahoo.com'),
'paid_indicators' => array(
'paths' => array('/cbclk'),
'refs' => array('yahoo_sem')
)
),
'duckduckgo' => array(
'domains' => array('duckduckgo.com'),
'paid_indicators' => array()
)
);
// Social Networks with paid indicators
$social_networks = array(
'facebook' => array(
'domains' => array('facebook.com', 'fb.com', 'fb.me', 'm.facebook.com'),
'paid_indicators' => array(
'params' => array('fbclid'),
'paths' => array('/ads/')
)
),
'instagram' => array(
'domains' => array('instagram.com', 'l.instagram.com'),
'paid_indicators' => array(
'paths' => array('/ads/')
)
),
'twitter' => array(
'domains' => array('twitter.com', 't.co'),
'paid_indicators' => array(
'params' => array('twclid'),
'paths' => array('/promote')
)
),
'linkedin' => array(
'domains' => array('linkedin.com', 'lnkd.in'),
'paid_indicators' => array(
'paths' => array('/ads/')
)
),
'youtube' => array(
'domains' => array('youtube.com', 'youtu.be'),
'paid_indicators' => array(
'paths' => array('/ads/')
)
),
'pinterest' => array(
'domains' => array('pinterest.com', 'pin.it'),
'paid_indicators' => array(
'paths' => array('/ads/')
)
),
'tiktok' => array(
'domains' => array('tiktok.com', 'vm.tiktok.com'),
'paid_indicators' => array(
'params' => array('ttclid'),
'paths' => array('/ads/')
)
)
);
// Email Providers
$email_providers = array(
'outlook' => array(
'domains' => array('outlook.com', 'outlook.live.com'),
'medium' => 'email'
),
'gmail' => array(
'domains' => array('mail.google.com'),
'medium' => 'email'
),
'yahoo-mail' => array(
'domains' => array('mail.yahoo.com'),
'medium' => 'email'
)
);
// Check search engines first
foreach ($search_engines as $engine => $data) {
foreach ($data['domains'] as $domain) {
if (strpos($referrer_host, $domain) !== false) {
$parsed['source'] = $engine;
// Check for paid indicators
$is_paid = false;
if (isset($data['paid_indicators'])) {
// Check URL parameters
if (isset($data['paid_indicators']['params'])) {
foreach ($data['paid_indicators']['params'] as $param) {
if (isset($params[$param])) {
$is_paid = true;
break;
}
}
}
// Check paths
if (!$is_paid && isset($data['paid_indicators']['paths'])) {
foreach ($data['paid_indicators']['paths'] as $path) {
if (strpos($referrer_path, $path) !== false) {
$is_paid = true;
break;
}
}
}
// Check referrer strings
if (!$is_paid && isset($data['paid_indicators']['refs'])) {
foreach ($data['paid_indicators']['refs'] as $ref) {
if (strpos(strtolower($referrer), $ref) !== false) {
$is_paid = true;
break;
}
}
}
}
$parsed['medium'] = $is_paid ? 'cpc' : 'organic';
return $parsed;
}
}
}
// Check social networks
foreach ($social_networks as $network => $data) {
foreach ($data['domains'] as $domain) {
if (strpos($referrer_host, $domain) !== false) {
$parsed['source'] = $network;
// Check for paid indicators
$is_paid = false;
if (isset($data['paid_indicators'])) {
// Check URL parameters
if (isset($data['paid_indicators']['params'])) {
foreach ($data['paid_indicators']['params'] as $param) {
if (isset($params[$param])) {
$is_paid = true;
break;
}
}
}
// Check paths
if (!$is_paid && isset($data['paid_indicators']['paths'])) {
foreach ($data['paid_indicators']['paths'] as $path) {
if (strpos($referrer_path, $path) !== false) {
$is_paid = true;
break;
}
}
}
}
$parsed['medium'] = $is_paid ? 'cpc' : 'social';
return $parsed;
}
}
}
// Check email providers
foreach ($email_providers as $provider => $data) {
foreach ($data['domains'] as $domain) {
if (strpos($referrer_host, $domain) !== false) {
$parsed['source'] = $provider;
$parsed['medium'] = 'email';
return $parsed;
}
}
}
// If no match found, use referrer host as source
$parsed['source'] = $referrer_host;
$parsed['medium'] = 'referral';
return $parsed;
}
/**
* Enqueue scripts
*
* Enqueue the plugin's JavaScript file and pass cookie values and settings to it
*/
public function enqueue_scripts() {
wp_enqueue_script(
'wp-referrer-tracker',
plugins_url('js/wp-referrer-tracker.js', __FILE__),
array('jquery'),
'1.0.0',
true
);
$options = get_option('wrt_settings', array(
'auto_fields' => true,
'field_prefix' => 'wrt_',
'form_plugin' => 'none',
'auto_insert' => false
));
// Pass cookie values and settings to JavaScript
$referrer_data = array(
'source' => $this->get_source(),
'medium' => $this->get_medium(),
'campaign' => $this->get_campaign(),
'referrer' => $this->get_referrer(),
'settings' => array(
'autoFields' => $options['auto_fields'],
'fieldPrefix' => $options['field_prefix']
)
);
wp_localize_script('wp-referrer-tracker', 'wpReferrerTracker', $referrer_data);
}
/**
* Get source
*
* Get the source value from the cookie
*
* @return string The source value
*/
private function get_source() {
if (!isset($_COOKIE['wrt_source'])) {
return '';
}
return sanitize_text_field(wp_unslash($_COOKIE['wrt_source']));
}
/**
* Get medium
*
* Get the medium value from the cookie
*
* @return string The medium value
*/
private function get_medium() {
if (!isset($_COOKIE['wrt_medium'])) {
return '';
}
return sanitize_text_field(wp_unslash($_COOKIE['wrt_medium']));
}
/**
* Get campaign
*
* Get the campaign value from the cookie
*
* @return string The campaign value
*/
private function get_campaign() {
if (!isset($_COOKIE['wrt_campaign'])) {
return '';
}
return sanitize_text_field(wp_unslash($_COOKIE['wrt_campaign']));
}
/**
* Get referrer
*
* Get the referrer value from the cookie
*
* @return string The referrer value
*/
private function get_referrer() {
if (!isset($_COOKIE['wrt_referrer'])) {
return '';
}
return esc_url_raw(wp_unslash($_COOKIE['wrt_referrer']));
}
/**
* Debug logging
*/
private function debug_log($message) {
if (defined('WP_DEBUG') && WP_DEBUG === true && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG === true) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
error_log('WRT: ' . $message);
}
}
/**
* Verify nonce for form data
*/
private function verify_nonce() {
if (!isset($_REQUEST['_wpnonce'])) {
return false;
}
$nonce = sanitize_text_field(wp_unslash($_REQUEST['_wpnonce']));
return wp_verify_nonce($nonce, 'wrt_form_action');
}
}
// Initialize the plugin
function wp_referrer_tracker_init() {
return WP_Referrer_Tracker::get_instance();
}
add_action('plugins_loaded', 'wp_referrer_tracker_init');