-
Notifications
You must be signed in to change notification settings - Fork 0
/
kntnt-session-campaign-parameters.php
93 lines (67 loc) · 2.13 KB
/
kntnt-session-campaign-parameters.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
<?php
/**
* @wordpress-plugin
* Plugin Name: Kntnt Session Campaign Parameters
* Plugin URI: https://github.com/Kntnt/kntnt-session-campaign-parameters
* Description: Provides API to retrieve Google or Matomo campaign parameters (i.e. UTM or MTM, respectively) sent during current session.
* Version: 1.0.0
* Author: Thomas Barregren
* Author URI: https://www.kntnt.com/
* License: GPL-3.0+
* License URI: http://www.gnu.org/licenses/gpl-3.0.txt
*/
namespace Kntnt\Session_Campaign_Parameters;
defined( 'ABSPATH' ) || die;
function parameters() {
return apply_filters( 'kntnt-session-campaign-parameters', [
// Google UTM parameters
'utm_source',
'utm_medium',
'utm_campaign',
'utm_id',
'utm_term',
'utm_content',
// Matomo MTM parameters
'mtm_campaign',
'mtm_cid',
'mtm_content',
'mtm_group',
'mtm_kwd',
'mtm_medium',
'mtm_placement',
'mtm_source',
] );
}
function get( string ...$params ) {
// Resume PHP session.
_initialize();
// Default to all parameters.
if ( ! $params ) {
$params = parameters();
}
// Extract values from requested parameters.
$vars = array_intersect_key( $_SESSION, array_flip( $params ) );
// Arrange the values as described in the README file.
$vars = count( $params ) == 1 ? ( $vars[ $params[0] ] ?? null ) : array_replace( array_fill_keys( $params, '' ), $vars );
return $vars;
}
function _initialize() {
// Start or resume PHP session.
@session_start();
// $_SESSION is not created automatically.
if ( ! isset( $_SESSION ) ) {
$_SESSION = [];
}
}
// Save any campaign parameters after all plugins are loaded, to allow
// implementation of the `kntnt-session-campaign-parameters` filter with code
// snippet plugins, and before the theme is loaded, to allow calling
// the `get()` function in functions.php.
add_action( 'setup_theme', function () {
if ( $params = array_intersect_key( $_GET, array_flip( parameters() ) ) ) {
// Start PHP session.
_initialize();
// Save values of all managed paramters that are present in the URL.
$_SESSION = array_merge( $_SESSION, $params );
}
} );