Action hook is very powerful WordPress feature. If you do any customization, create plugin or develop theme then this is very important feature you can’t miss out.
What are hooks?
According to WordPress:
“Hooks are provided by WordPress to allow your plugin to ‘hook into’ the rest of WordPress; that is, to call functions in your plugin at specific times, and thereby set your plugin in motion.”
In other words, Action hooks are essentially placeholders in your template files. Wherever an action hook is placed, it will execute any code that has been “hooked” to it. They sit there until you instruct them to do some task for you either by using Action or Filter hooks.
There are two default WordPress action hooks which every theme needs to add. They are wp_head
just before ending and wp_footer
. They’re simply placeholders that plugins and themes can use to insert code into the head and footer of the theme.
How to use Action Hook?
You need to define your custom hook first.
You do this by calling an action hook, do_action()
For example: Lets say you want ‘Hello World’ to display before the footer sidebar area of your theme. For that you’ll need to create do_action
hook in footer.php before the footer sidebar area.
<?php do_action('before_footer_sidebar') ?>
So, this will create a hook in your footer.php before the footer sidebar area(assuming you kept the hook before the footer sidebar area).
Now, in the functions.php you need to create a function
to display ‘Hello World’.
<?php function hello_world() { ?> <div id="hello-world"> <p>"Hello World"</p> </div> <?php } ?>
This is where add_action()
enters. Below your function you will have to add the following code:
add_action('before_footer_sidebar','hello_world');
This will display Hello World before the footer sidebar. Previously we had added a hook on footer.php before the footer sidebar area. That’s the place where this gets executed.
To put it simply:
do_action()
is a place where function gets executed.
add_action()
executes the function to that place.