Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggreagtion Enquires Welcome

Include The Facebook Pixel Tracking Code In Your WordPress Head

I follow a few "low-end" Facebook groups focused on marketing and best-practice advertising. I'm not sure why I do because the misguided information only further fuels my disdain for that segment of the marketing community that really doesn't have a clue what they're doing. Anyhow, one of the questions that pops up from time-to-time is how to enter the Facebook tracking pixel into the head of a WordPress website. Since you'll be using the pixel on every page of your website, using the wp_head action to render the code is appropriate.

Only use a plugin if you absolutely need additional features and functionality, and never just add the code to a core file (around half of the clueless contributors to the thread in question tend to advocate this nonsense). If you're a client, our full-featured plugin includes all the pixel-related features you'll ever need; activate from your control panel.

The Code

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin.

1
<?php 
2
/*
3
    Include The Facebook Pixel Tracking Code In Your WordPress Head
4
    http://www.beliefmedia.com/code/wp-snippets/facebook-pixel
5
*/
6
 
7
 
8
function beliefmedia_facbeook_tracking_pixel() {
9
 
10
 /* Enter your Facebook Pixel ID here */
11
 $pixel_id = '128710237825530';
12
 
13
?>
14
<!-- Facebook Pixel Code -->
15
<script>
16
  !function(f,b,e,v,n,t,s)
17
  {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
18
  n.callMethod.apply(n,arguments):n.queue.push(arguments)};
19
  if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
20
  n.queue=[];t=b.createElement(e);t.async=!0;
21
  t.src=v;s=b.getElementsByTagName(e)[0];
22
  s.parentNode.insertBefore(t,s)}(window, document,'script',
23
  'https://connect.facebook.net/en_US/fbevents.js');
24
  fbq('init', '<?php echo $pixel_id; ?>');
25
  fbq('track', 'PageView');
26
</script>
27
<noscript><img loading="lazy" height="1" width="1" style="display:none"
28
  src="https://www.facebook.com/tr?id=<?php echo $pixel_id; ?>&ev=PageView&noscript=1"
29
/></noscript>
30
<!-- End Facebook Pixel Code -->
31
<?php
32
}
33
add_action('wp_head', 'beliefmedia_facbeook_tracking_pixel');

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment