Webtecho Blog

WordPress Hooks and filters explained

in General

WordPress talks a lot about Hooks and filters. Even if you are not a techie, its a good idea to understand basics of what are hooks and filters. Why?

  • Themes like thesis use custom hooks and filters a lot. If you don’t know what they are , you will find some difficulty in arranging elements on your blog
  • It will give you more confidence on understanding how wordpress works
  • It is fun.

WordPress Hooks: But how?

A hook is nothing but a call to an external function at appropriate place during wordpress runtime. For e.g when you load an admin page (let us say to customize a plugin) a lot of admin hooks are called. These hooks initialize the wordpress admin page. They might for example load scripts and styles to the admin page to enhance the functionality.

When a blog reader loads a page on your blog, internally your wordpress is also loading a number of hooks. They could be located in

  • header of your page
  • content section
  • Footer
  • Sidebars
  • …..

During run time these hooks call up functions ( both standard that come with wordpress and custom written by you, theme authors or plugin authors). The function introduce additional functionalities.

Let us say you want to introduce meta tags in your blog but do not want to modify the theme files .

You will write something like
then you will declare a function somewhere in functions.php if you are using standard themes.


add_action(‘wp_head’, ‘add_meta_tags’);


add_meta tags()

{

//echo  ‘<meta type=”….”>

}

What this does that is when wordpress is loaded , your function will get called and meta type will be placed in the header. Thus it is possible to inject code at certain places where wordpress calls these action hooks. Doesn’t it make life simpler.

One important parameter that is not shown above is third one which indicates the position of your defined function if there are other plugins that are also calling the hook. If you call a hook twice for example, you can add the number as the third argument to specify which function gets called first

add_action(‘wp_head’, ‘add_meta_tags’, 5 );

add_action(‘wp_head’, ‘add_more_meta_tags’,10 );

add_meta_tags will be called earlier than add_more_meta_tags.

There are a number of hooks provided by wordpress. You may define your own hooks as well. Thesis has a number of hooks to help you create a great website.

{ 0 comments… add one now }

Leave a Comment

Next post: