1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Module Name: Cloudflare Analytics |
4
|
|
|
* Module Description: Let WPCOM users automatically insert a Cloudflare analytics JS snippet into their site header. |
5
|
|
|
* Requires Connection: Yes |
6
|
|
|
* Auto Activate: No |
7
|
|
|
* |
8
|
|
|
* @package automattic/jetpack |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Bail if accessed directly |
13
|
|
|
*/ |
14
|
|
|
if ( ! defined( 'ABSPATH' ) ) { |
15
|
|
|
exit; |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* WP_Cloudflare_Analytics class. |
20
|
|
|
*/ |
21
|
|
|
class WP_Cloudflare_Analytics { |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Manages the insertion of Cloudflare analytics snippets into a user's |
25
|
|
|
* site <head>. |
26
|
|
|
* |
27
|
|
|
* @var WP_Cloudflare_Analytics Static property to hold our singleton instance |
28
|
|
|
*/ |
29
|
|
|
private static $instance = false; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Constructor method |
33
|
|
|
* Causes Cloudflare JS snippet to be included during head rendering. |
34
|
|
|
*/ |
35
|
|
|
public function __construct() { |
36
|
|
|
add_action( 'wp_head', array( $this, 'insert_code' ), 999 ); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Function to instantiate our class and make it a singleton |
41
|
|
|
*/ |
42
|
|
|
public static function get_instance() { |
43
|
|
|
if ( ! self::$instance ) { |
44
|
|
|
self::$instance = new self(); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
return self::$instance; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* This injects Cloudflare analytics code into the footer of the page. |
52
|
|
|
* Called exclusively by wp_head action |
53
|
|
|
*/ |
54
|
|
|
public function insert_code() { |
55
|
|
|
$option = get_option( 'cloudflare_analytics' ); |
56
|
|
|
$tracking_id = isset( $option['code'] ) ? $option['code'] : ''; |
57
|
|
|
if ( empty( $tracking_id ) ) { |
58
|
|
|
echo "<!-- Your Cloudflare Analytics Plugin is missing the tracking ID -->\r\n"; |
59
|
|
|
return; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
// If we're in the admin_area, return without inserting code. |
63
|
|
|
if ( is_admin() ) { |
64
|
|
|
return; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
$this->render_code( $tracking_id ); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* Renders Cloudflare analytics code snippet. |
72
|
|
|
* |
73
|
|
|
* @param string $tracking_id Cloudflare Analytics tracking ID. |
74
|
|
|
*/ |
75
|
|
|
private function render_code( $tracking_id ) { |
76
|
|
|
printf( |
77
|
|
|
"<!-- Cloudflare Web Analytics --> |
78
|
|
|
<script defer |
79
|
|
|
src='https://static.cloudflareinsights.com/beacon.min.js' |
80
|
|
|
data-cf-beacon='{\"token\": \"%s\"}'> |
81
|
|
|
</script> |
82
|
|
|
<!-- End Cloudflare Web Analytics -->\r\n", |
83
|
|
|
esc_html( $tracking_id ) |
84
|
|
|
); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|