Watch those hook priorities

When adding an action or a filter to WordPress, the third parameter allows you to adjust priority. In this way, multiple bits of code can determine the order that they should execute without having to rely on the order that PHP actually parses them.

Generally, there are no minimums or maximum limits (other than those imposed by PHP itself) for priority, but there’s a very good reason to give consideration to when your code runs. Here’s an example:

Widget registration should be hooked to ‘widgets_init’ as in the following code:

function mytheme_register_widgets() {
  register_widget( 'Mytheme_Widget' );
add_action( 'widgets_init', 'mytheme_register_widgets' );

This is also the hook used internally by WordPress to take all the registered widgets and create a global array, $wp_registered_widgets. Specifically, this is in the WP_Widget_Factory class’s constructor function which is called once in wp-settings.php, immediately before the ‘setup_theme’ action hook.

class WP_Widget_Factory {
	var $widgets = array();

	function WP_Widget_Factory() {
		add_action( 'widgets_init', array( $this, '_register_widgets' ), 100 );

Any widget registered after the _register_widgets function has run will not show in the admin.

If you are writing a plugin:
add_action( 'widgets_init', 'mytheme_register_widgets', 100 ); will work because plugins are loaded prior to do_action( 'setup_theme' ). What it also means is that folks writing a theme or modifying functions.php will not be able to unregister your widget.

If you are writing a theme:
add_action( 'widgets_init', 'mytheme_register_widgets', 100 ); will not work. Themes are loaded after WP_Widget_Factory’s constructor method.

I can’t imagine any reason to register a widget with priority 100, but there are very legitimate reasons for unregistering a widget. So my advice:

  • Register your widgets at or near priority 10 (the default)
  • If you are writing a plugin, never register a widget a priority 100
  • Registering a plugin at a priority above 100 just flat-out won’t work.
  1. […] Watch those hook priorities » […]

Leave a Comment

Finely crafted websites & tools that make the web better.