Free Signup |
Login

Not a member? Join for free.

Smarter Thesis Hooks

by Adam Barber on March 26, 2010

Here’s a quick tip to keep your custom_functions.php file organized, by using smarter hooks.

The Old Way

When most people add new functions to Thesis they create a new function, and use

add_action('thesis_hook_here','your_function_here');

This means works pretty well for a small number of hooks (say 10 or less, I find), but when developing custom skins, or complex sites for clients, I find I can end up with A LOT of functions that all need to go to different places and use a lot of conditional tags to set correct placement. Done the normal way, it looks like this

function custom_home_page_function() {
  if(is_front_page()) {
    echo 'This is only going on the front page.';
  }
}    

function custom_home_page_function2() {
  if(is_front_page()) {
    echo 'This is only going on the front page, but in a second spot.';
  }
} 

function custom_home_page_function3() {
  if(is_front_page()) {
    echo 'This is only going on the front page, but in a third spot.';
  }
}
add_action('thesis_hook_here','custom_home_page_function');
add_action('thesis_hook2_here','custom_home_page_function2');
add_action('thesis_hook3_here','custom_home_page_function3');

The New Way

Seems easy enough, but if you look carefully, you’ll see that the “is_front_page” check is being repeated for each function. When possible, you should always try to avoid repeating yourself when writing code. This doesn’t do that. In fact, with the conditional tag in each function, you may end up repeating it dozens of times. Not good. Instead, we’ll do the following

function custom_home_page_function() { echo 'This is only going on the front page.';}
function custom_home_page_function2() { echo 'This is only going on the front page, but in a second spot.';}
function custom_home_page_function3() { echo 'This is only going on the front page, but in a third spot.';}     

function front_page_functions() {
if(is_front_page()) {
  add_action('thesis_hook_here','custom_home_page_function');
  add_action('thesis_hook2_here','custom_home_page_function2');
  add_action('thesis_hook3_here','custom_home_page_function3');
} }       

add_action('wp', 'front_page_functions');

Now we only have one conditional tag (on front_page_functions), which cuts down on code duplication. Your code will be easier to manage as well. Now, to add a new add a new function to the front page, just add your “add_action” to the front page group. Everything is grouped together for easy adjustments down the road.

Still Have Questions?

Great! Get in touch with me and I'll help you out. In addition to writing tutorials and developing some of the most widely used Thesis Skins, I'm also available for hire.

Leave a Comment

{ 1 trackback }

Previous post:

Next post: