Small edits to the header in a WordPress Child Theme, adding Google Analytics Tracking Code

Suppose you’re interested in making very slights changes to your WordPress Child Theme. You could, of course, override the header.php file of your parent theme, but that’s not the path WordPress would advise you to take (why miss the possible future upgrades of the parent theme?) The better solution would be: Hooks.
The wise developers of WordPress made sure that there are lots of places where you could “hook” to call your own function. We show below the simplest example, using the hook “wp_head”, usually called by header.php right before the closing </head> tag. Here is the simplest example, working with your Child Theme’s functions.php file. Make sure your functions.php file has these lines of code: <!-- This is already some HTML (an HTML comment, to be exact) that will appear in every page in your site. This is the right place to make your little edits to your Child Theme. For example, you could delete this HTML comment and instead paste here the Tracking Code you got from Google, to make it appear before the </head> in every page! --> The add_action line asks WP to call your function (‘my_add_stuff_to_head‘ in our example) upon reaching the wp_head hook. That’s it. Recall that you can “mix” HTML and PHP in the way shown above. Final important notes:
  • WARNING: If you don’t feel 100% confident when making changes to your PHP files, be extra careful this time… Make sure you don’t have ANY mistakes / typos when editing the important functions.php file, because if you introduce an error to the functions.php file, your WordPress dashboard will not work as well: You will not be able to access your site or the dashboard (not even as admin). That is, until you correct that bug you just created, but this time using some alternative way to access your files, e.g. via FTP.
  • Read more about add_action here.
  • wp_head is just one action hook. The list of the action hooks available for use in plugin development is found here.
  • Finally, there are other examples out there in the web. Enjoy the hooking and all the action… 😉