Before you
know what action hooks are I hope you have a basic understanding of hooks, if not click here to go to my WordPress Hooks Page.
Introduction
In short Action Hooks are features which allows developers to modify features in
WordPress without having to touch core files. These are also very handy when developing our own custom codes. This
way we can give access to developers to add, remove or customize a feature of our plugin or theme.
This
way developers do not need to touch our core files, they can easily make their own files and add changes as
needed. We will focus on three types of action hooks in this chapter
add_action()
This hook has four parameters add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1);
out of which the first two($tag
and $function_to_add
) are required and rest two ($priority
and
$accepted_args
) are optional $tag is the name of the action hook that you will be using in
do_action(), to which $function_to_add will be hooked into. $function_to_add is the name
of the function that we will be adding to $tag. Sounds confusing? The example below should give you a better idea
function my_hook_function(){ echo 'I will be hooked into my_custom_hook'; } add_action('my_custom_hook','my_hook_function');The above code now adds the features of the function
my_hook_function()
into the hook my_custom_hook.
Now in order to use the hook all you have to do is use it in do_action() likedo_action('my_custom_hook')
do_action()
This hook has two parameters
do_action( string $tag, $arg = '' )
out of which $tag is required and $args is optional
$tag is the name or the value of the $tag inadd_action()
.
It’s easy as usingdo_action('my_custom_hook')When you use this code it will show the output of the function
my_hook_function()
remove_action()
Our first two hooks were used to create an action hook and then display the output. What if we want to remove the
output of the hook?For that weremove_action()
hook. This hook helps to remove the features or
factions that we have added to a hook used in do_action()
remove_action( $tag, $function_to_remove, $priority );
out of which only the first two $tag
and $function_to_remove are required, the third $priority is optional$tag is the name of the hook we want to target or im simple terms the name that we have provided in
do_action()
and $function_to_remove is name of the function that has been hooked using the
add_action()
.
In the above example we have usedadd_action()
to create a hook my_custom_hook and add a
feature my_hook_function into that hook which an be shown usingdo_action()
remove_action('my_custom_hook','my_hook_function').
You have successfully remove the feature of the function my_hook_function from the hook
my_custom_hook.More information the priorities and other optional values will be added soon.
Please do let me know if you have
any confusions regarding actions hooks please leave a comment and I will provide
as much information as I can.