Adding Custom Code Into WordPress’ Header
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:
1 2 3 4 5 |
function my_head_function() { echo 'Ooooh I'm in the WordPress Head!'; } add_action('wp_head', 'my_head_function'); |
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
Rob Cubbon
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.
Paul Robinson
No problem. Glad it was helpful. 🙂