Quick Tip: Add tracking code to header

image_pdfimage_print

Let’s say you need to add Google Analytics code, a Facebook pixel, or other tracking code to the head of every page on your site. While there are plenty of plugins you can use to do this, you may be like me in that you try to keep the number of plugins you run to a minimum.

In this case, it’s very easy to add tracking with just a few lines of PHP in your theme’s functions.php file. (For a longer explanation of this method, check out this article.)

Whether you edit your functions file using your favorite text editor or in WordPress via Appearance > Theme Editor, the code you need is very basic, and amounts to three lines of PHP plus your tracking code. The snippet below looks pretty long, but that’s only because I added some comments to explain what’s going on and a bunch of space to make it easier to read.

To explain that last line a little bit:

  • wp_head is where you want this code to be inserted,
  • add_tracking_info_to_head is the function we just created,
  • and a high priority number makes this code insertion happen just before the opening tag

If you have any questions about this, feel free to ask in the comments.

stuff we dig

FYI: yes, the above are affiliate links, so we do make a small amount of money if you follow them over and buy what they're selling. Thank you for helping pay our hosting costs!

Dave Kuhar

Dave runs Transmit Studio, a media creation lab in San José. He's built more websites with WordPress than he can remember. He likes hearing himself talk and writing about himself in third person.

Leave a Comment