Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggregation 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
function beliefmedia_facbeook_tracking_pixel() {
8
 
9
 /* Enter your Facebook Pixel ID here */
10
 $pixel_id = '128710237825530';
11
 
12
?>
13
<!-- Facebook Pixel Code -->
14
<script>
15
  !function(f,b,e,v,n,t,s)
16
  {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
17
  n.callMethod.apply(n,arguments):n.queue.push(arguments)};
18
  if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
19
  n.queue=[];t=b.createElement(e);t.async=!0;
20
  t.src=v;s=b.getElementsByTagName(e)[0];
21
  s.parentNode.insertBefore(t,s)}(window, document,'script',
22
  'https://connect.facebook.net/en_US/fbevents.js');
23
  fbq('init', '<?php echo $pixel_id; ?>');
24
  fbq('track', 'PageView');
25
</script>
26
<noscript><img loading="lazy" height="1" width="1" style="display:none"
27
  src="https://www.facebook.com/tr?id=<?php echo $pixel_id; ?>&ev=PageView&noscript=1"
28
/></noscript>
29
<!-- End Facebook Pixel Code -->
30
<?php
31
}
32
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