How to use WordPress hooks

Commentary

We love it when other people save us time.

And that’s just what Smashing Magazine has done with its post on WordPress hooks.

The only thing we’d really add to the amazing writeup is that you can save a lot of coding by using closures, which are supported in PHP 5.3.

For example, instead of doing this:

[php] function gunner_wp_head() { echo "HI World"; } add_action("wp_head","gunner_wp_head"); [/php]

You can do:

[php] add_action("wp_head",function() { echo "HI World"; }); [/php]

Also, hooks are extremely important for child themes.

We use one common parent theme for all our WordPress sites and extend it with child themes with heavy use of custom hooks.

Finally, the post talks about naming your functions to avoid function collisions. A better way to do that is through class encapsulation.

[php] class emailer { function send($post_ID) { $friends = 'bob@example.org,susie@example.org'; mail($friends,"sally's blog updated",'I just put something on my blog: http://blog.example.com'); return $post_ID; } } $myEmailClass = new emailer(); add_action('publish_post', array($myEmailClass, 'send')); [/php]

Leave a Reply