Adding Custom Code Into WordPress’ Header

/ Wordpress / by Paul Robinson / 2 Comments
This post was published back on March 24, 2010 and may be outdated. Please use caution when following older tutorials or using older code. After reading be sure to check for newer procedures or updates to code.

Well all know you could just crack open that header.php file & hard code all that info into your file, but sometimes there’s no substitute for keeping your template files as clean as possible, there is also the possibility that the code that you are building a plugin & you need to inject code into the head, big problems with editing the theme files there.

To get around this WordPress has hooks. You can use these to tell WP to execute a function you specify when it reaches that point in the loading of WordPress. So in this example we would use the wp_head hook. Here’s how it looks:

Obviously you would probably have your code do something more spectacular than that, but it just show’s how it’s done. There is one huge caveat, if you are developing a plugin & the users theme does not have in it, this will not work. Most good themes have it in place, but there are still some that do not.

On a side note, this entire tutorial can also be used to work with the footer using the hook wp_footer.

I’ve decided to record a video to help better illustrate how to do this. Unfortunately no sound as I’m having problems with the sound on my capture program. Full screen the video to get HD quality (was captured at 1440×900 and is scaled down).

[pro-player width=”560″ height=”350″ type=”mp4″]http://return-true.com/wp-content/uploads/videos/AddingCodeToWPHead.mp4[/pro-player]

I hope this tip has helped you, and there will be more written, and hopefully, more video tutorials soon. As I said for some reason my screen capture program has just decided it doesn’t want to record audio… It crashes every time it tries to save. 🙁

2 Comments

Author’s gravatar

Hi Paul, Thanks for that. I’m creating a child theme for 2010. I used this to enter the Google Analytics code and favicon.ico call into the head. It’s going to be hard to find the code to put into functions.php to do stuff but this is a great start.

Reply
Older Comments
Newer Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I'll keep your WordPress site up-to-date and working to its best.

Find out more