Analytics: Add Facebook Meta Pixel Tracking Script to WordPress

Analytics add facebook meta pixel tracking script to wordpress image

Up your analytics game in the metaverse, bro!

What it does…

Adds Facebook / Meta pixel tracking script to your site. NOTE: You’re gonna wanna add your own unique FB Meta Pixel ID in the code, then let this snip take care of the rest.

How it does it…

Adds the tracking JavaScript code to the head of your site using `wp_head`, but only on Production (if using Env555), and only for logged-in users. (But you could edit those parts, if desired.)

See the code…

<?php

// Analytics: Add Facebook Meta Pixel Tracking Script to Wordpress
// https://snipsnip.pro/s/164
/* Uses Env555, if available */
namespace NThgdKCU;

\add_action( 'wp_head', function () { 

    $fbID = "XXXXXXXXXXXX";
    
    $addCode = true;
	if (function_exists('\Env555\this_is_a_production_site')) { 
	    // only on production for logged out users
    	$addCode = (\Env555\this_is_a_production_site() && !\is_user_logged_in());
	}
	
	if ($addCode === true) {
?>

<!-- Analytics: Add Facebook Meta Pixel Tracking Script to Wordpress - https://snipsnip.pro/s/164 -->
<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 $fbID; ?>");
	fbq('track', 'PageView');
</script>
<noscript>
	<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=<?php echo $fbID; ?>&ev=PageView&noscript=1"/>
</noscript>

<?php } }, 1000 );

Leave a Reply

Your email address will not be published. Required fields are marked *