CHAPTER 6 • Advanced Theme Usage 157
HOOKING ON
If you want to hook on to one of WordPress’s action hooks, say by adding some web statistics
code to the wp_footer hook, you can do it in functions.php. You write a PHP function
containing the stuff you want to add, and then you add it to the hook.
Start with the function. The actual analytics script code is just nonsense, so if you want to use
this particular hook you should, of course, swap the code for your own:
<?php function my_webstats() { ?>
This gives you the my_webstats() function to use, loaded with the (obviously faulty)
script tag. This is what you want to hook on to wp_footer. Notice how I cut the PHP tag
to make it easier to manage the HTML. You hook on by using the add_action function and
placing it before the actual function:
add_action( 'wp_footer', 'my_webstats' );
You’re telling add_action that you want to add a function to wp_footer (the first
parameter), and then you declare which function, my_webstats in this case (the second
parameter), you want to add. The full code would look like this, in your functions.php file:
<?php
add_action( 'wp_footer', 'my_webstats' );
function my_webstats() {
?>
This would add the script at the end of your theme when loaded. Some excellent WordPress
hookery right there.
CREATING YOUR OWN ACTION HOOKS
Creating your own action hooks is easy. First, you create your PHP function as you did before.
It can be anything, really: a simple echo or something way more advanced. The only differ-
ence between creating and using your own action hooks, compared to the built-in ones, is
that you need to add them to your theme. Remember, wp_head and wp_footer already sit
there, so there’s no need to add them, but your brand-new action hook won’t be so lucky.
The code for adding action hooks is simple:
<?php do_action( 'the-name-of-the-hook' ); ?>