Wordpress - How to know what priority to use with add_action()?
range of priority values? range of priority values?
Generally, speaking, you can't know a priori what priority something is hooked with. The priority needed depends on how other callbacks where hooked in. Often that is the default value of 10 but it could be anywhere between PHP_INT_MIN
(negative integers are still integers) and PHP_INT_MAX
and there is no way to be sure except by experiment and, if possible (as with the Core and any themes or plugins that you are specifically concerned with), by examining the source.
WordPress puts your actions into an array with an indexed priorities. You can see this by printing out ( in the admin panel admin_init
) $wp_filter
:
*Note* as @s_ha_dum points out in the comments below, admin_init
may not catch all added hooks into the action, the more reliable print out may be hooking into shutdown
instead.
function filter_print() {
global $wp_filter;
print_r( $wp_filter['admin_bar_menu'] );
die();
}
add_action( 'admin_init', 'filter_print' );
This gives us a neat array that looks something like this: ( simplified )
Array(
[admin_bar_menu] => Array (
[0] => Array (
[wp_admin_bar_my_account_menu] => Array (
[function] => wp_admin_bar_my_account_menu
[accepted_args] => 1
)
[wp_admin_bar_sidebar_toggle] => Array (
[function] => wp_admin_bar_sidebar_toggle
[accepted_args] => 1
)
)
[4] => Array (
[wp_admin_bar_search_menu] => Array (
[function] => wp_admin_bar_search_menu
[accepted_args] => 1
)
)
[7] => Array (
[wp_admin_bar_my_account_item] => Array (
[function] => wp_admin_bar_my_account_item
[accepted_args] => 1
)
)
[10] => Array (
[wp_admin_bar_wp_menu] => Array (
[function] => wp_admin_bar_wp_menu
[accepted_args] => 1
)
)
[20] => ...
)
)
The 0, 4, 7, 10, and so forth are the priorities of the actions, when a new action is added it's defaulted to 10, similar to index 0 in the example above, they are just stacked into the same index of the array. Considering that many hooks are added into this particular action you would want to at the very end or at last after a specific action was run ( such as menus ). 1 of the two priorities could also work just as effectively: 81
or 201
.
For the most part, the default priority of 10 is sufficient enough. Other times you want to add your hook direct after another ( to maybe nullify it's purpose or remove a specific item ) at which case you can use the global $wp_filter;
to figure out where it needs to go.
Well, there's a way to find the priority of an action.
we can use the following codehas_action( $tag, $function_to_check )
which Optionally returns the priority on that hook for the specified function.
Ref: https://codex.wordpress.org/Function_Reference/has_action