How to know what priority to use with add_action()?

I was writing a small plugin to remove some menu items for non-admin users from the backend, and discovered that my plugin didn’t do anything unless I specified a priority in my code:

add_action('admin_bar_menu', 'remove_toolbar_items', 999);

Without the 999, the code doesn’t remove the items in my remove_toolbar_items function, and with it it works great:

function remove_toolbar_items( $wp_admin_bar ) {
    if ( !current_user_can( 'manage_options' ) ) {
        $wp_admin_bar->remove_node('new-post');
        $wp_admin_bar->remove_node('comments');
    }
}

The docs for the priority parameter state:

Used to specify the order in which the functions associated with a
particular action are executed. Lower numbers correspond with earlier
execution, and functions with the same priority are executed in the
order in which they were added to the action. Default value: 10

However I didn’t find anything that explains how you’re supposed to determine what priority to use. How do you determine when to use priority, and what priority to use? I feel like I could’ve been scratching my head for hours if I hadn’t toyed around with the priority parameter.

Also, I see that the default priority is 10, but is there a known range of priority values?

4

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.

Leave a Comment