Sequence of do_action & add_action using WP hooks

I was trying to hook add_action into one of the plugins do_action, however was not able to get it done until I realized that they have a sequence to be followed! In this post I will give some examples to understand this unexpected behavior and how to make it expected.

Wrong way of adding add_action for do_action

The following code does not work as expected:

function function_do_action() {
$var1 = 11111;
echo $var1;
do_action('call_do_action');

}

function function_add_action() {
$var2 = 22222;
echo $var2;
add_action('call_do_action', 'call_linked_function');
}

function call_linked_function() {
$var3 = 33333;
echo $var3;
}

function_do_action();
function_add_action();

This is because do_action is called before add_action. So it does not get hooked up.

If we change the position of function_do_action and move it below function_add_action, it works, like this:

function function_do_action() {
$var1 = 11111;
echo $var1;
do_action('call_do_action');

}

function function_add_action() {
$var2 = 22222;
echo $var2;
add_action('call_do_action', 'call_linked_function');
}

function call_linked_function() {
$var3 = 33333;
echo $var3;
}

function_add_action();
function_do_action();

Using WordPress hooks to run add_action for do_action

One more common way and problem related to hooks and filters in WordPress is when we are using them through other WordPress hooks and filters.

For example, this code does not work:

function function_do_action() {
$var1 = 11111;
echo $var1;
do_action('call_do_action');

}

function function_add_action() {
$var2 = 22222;
echo $var2;
add_action('call_do_action', 'call_linked_function');
}

function call_linked_function() {
$var3 = 33333;
echo $var3;
}

add_action('init','function_do_action');
add_action('init','function_add_action');

However if we change the sequence here too, it will work. However better option is to change the priority and make function_add_action run first and then function_do_action be called, like this:

function function_do_action() {
$var1 = 11111;
echo $var1;
do_action('call_do_action');

}

function function_add_action() {
$var2 = 22222;
echo $var2;
add_action('call_do_action', 'call_linked_function');
}

function call_linked_function() {
$var3 = 33333;
echo $var3;
}

add_action('init','function_do_action',2);
add_action('init','function_add_action',1);

I hope it helps. Let me know if you need my help in fixing any issue related to wordpress filters and hooks.

The same code and logic applies to do_filter and add_filter too.

Leave a Reply

Your email address will not be published.