Google Analytics & Facebook Pixel Without a Plugin

google analytics

Most commercial websites will want to have some sort of tracking/analytics on them. Use the data from these tools to improve your website. Make it easier for your visitors to find what they’re looking for. Sell more product. WordPress already has lots of plugins that will add these tools to your website. Here, we’ll add Google Analytics and Facebook Pixel to your WordPress website, without needing to reference a third-party plugin.

If you don’t have a functions.php then you should make sure you’re working on a custom child theme before continuing.

Let’s Write the Code

We’re going to try and keep our new code nice and tidy here by creating a new file for the analytics functions we’re going to write. Then, we’re going to link to this new file from our custom child theme’s functions.php file.

Create a new file in your custom child theme called functions-analytics.php and paste the following into it.

<?php

/**
 * Support various analytics trackers and add relevant code to our
 * headers/footers.
 *
 * https://headwall-hosting.com/docs/
 */

// Block direct access.
if (!defined('WPINC')) {
	exit('Do NOT access this file directly.');
}

function hw_add_google_analytics($tracker_code = '') {
	global $hw_google_analytics_tracker;
	global $hw_is_google_analytics_enabled;

	$hw_google_analytics_tracker = $tracker_code;
	$hw_is_google_analytics_enabled = !empty($tracker_code) && is_string($tracker_code);
}

function hw_add_facebook_pixel($pixel_id = '') {
	global $hw_facebook_pixel_id;
	global $hw_is_facebook_pixel_enabled;

	$hw_facebook_pixel_id = $pixel_id;
	$hw_is_facebook_pixel_enabled = !empty($hw_facebook_pixel_id) && is_string($hw_facebook_pixel_id);
}

function hw_headers_analytics() {
	$is_user_an_administrator = current_user_can('administrator');
	if (!$is_user_an_administrator) {
		// Do we need to inject Google ANalytics code?
		global $hw_is_google_analytics_enabled;
		global $hw_google_analytics_tracker;
		if ($hw_is_google_analytics_enabled && !empty($hw_google_analytics_tracker)) {
			hw_ga();
		}

		// Do we need to inject Facebook Pixel code?
		global $hw_is_facebook_pixel_enabled;
		global $hw_facebook_pixel_id;
		if ($hw_is_facebook_pixel_enabled && !empty($hw_facebook_pixel_id)) {
			hw_fbp();
		}
	}
}
add_action('wp_head', 'hw_headers_analytics', 20);

function hw_ga() {
	global $hw_google_analytics_tracker;

	echo "\n<!-- Global site tag (gtag.js) - Google Analytics -->\n";
	printf('<script async src="https://www.googletagmanager.com/gtag/js?id=%s"></script>', $hw_google_analytics_tracker);
	?><script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', "<?php echo $hw_google_analytics_tracker; ?>" );
</script><?php
}

// Facebook Pixel.
function hw_fbp() {
	global $hw_facebook_pixel_id;

	?><!-- Facebook Pixel Code --><script>
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window,document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
 fbq('init', '<?php echo $hw_facebook_pixel_id ?>');
fbq('track', 'PageView');
</script>
<noscript>
 <img height="1" width="1"
src="https://www.facebook.com/tr?id=<?php echo $hw_facebook_pixel_id; ?>&ev=PageView
&noscript=1"/>
</noscript><!-- End Facebook Pixel Code --><?php
}

This file does all the hard work for us. All we need to do now is link to it from our custom child theme’s functions.php file. Edit functions.php and add this somewhere near the top.

// Load functions to add Google and other analytics script blocks.
require_once dirname( __FILE__ ) . '/functions-analytics.php';

That gives us access to the following new functions:

  • hw_add_google_analytics()
  • hw_add_facebook_pixel()

Now all you need to do to add your Google Analytics tracker to your website is add something like this in your functions.php (after you’ve “required” the functions-analytics.php file).

// Add Google Analytics tracker.
hw_add_google_analytics( 'UA-9999999-1' ); // << Replace with your UA tracker code.

OR… Technically you could just set a couple of global variables somewhere in your functions.php file to get the same result…

$hw_google_analytics_tracker = 'UA-9999999-1';
$hw_is_google_analytics_enabled = true;

…but it’s cleaner to call the hw_add_google_analytics() function. Better practice.

If you look through functions-analytics.php, you’ll see we’ve got some code in there to see if the current user is an administrator. If they are, we don’t inject any tracker code into our pages. It’s a nice little touch to avoid skewing your stats on low-traffic sites when you’re doing some work on them.

That’s it – just a quickie way of injecting tracker code in your WordPress pages, without having to look for multiple plugins to do it for you… and you can reuse functions-analytics.php in your other WordPress projects too.

Happy tracking! 🙂

Like This Tutorial?

Let us know

WordPress plugins for developers

Leave a comment