WP-Mix

A fresh mix of code snippets and tutorials

WordPress widget_init not working

Working on USP Pro, I noticed that the included Form Widget stopped working. It didn’t display at all, like it wasn’t even registering with WordPress. After some investigating, I discovered that changes in the WordPress core required an update to the widget code. This article explains the process of troubleshooting and the working solution.

Scenario

In the plugin core file, I had the following code:

function usp_pro_init() { 
	$USP_Pro = new USP_Pro;
}
add_action('init', 'usp_pro_init', 1);

..and then in the USP_Pro class:

require_once(sprintf("%s/inc/usp-forms.php", dirname(__FILE__)));

..which includes the widget class:

class USP_Form_Widget extends WP_Widget {
	...
}
add_action('widgets_init', create_function('', 'register_widget("USP_Form_Widget");'));

Testing

After testing with the example widget provided in the WP Codex, it was clear that the issue was not with the widget class but rather in how/when the class is called. So after troubleshooting by changing:

require_once(sprintf("%s/inc/usp-forms.php", dirname(__FILE__)));

..to:

require_once(sprintf("%s/inc/usp-widget.php", dirname(__FILE__)));

..and including it directly like so in the plugin core file:

function usp_pro_init() { 
	$USP_Pro = new USP_Pro;
}
add_action('init', 'usp_pro_init', 1); 
require_once(sprintf("%s/inc/usp-widget.php", dirname(__FILE__)));

..such that the widget class is included after the init hook, it worked normally. But I wanted to include the widget from within the USP_Pro class.

Solution

After consulting the WP Codex on action hooks, I noticed this info:

init – Typically used by plugins to initialize. The current user is already authenticated by this time.

widgets_init – Used to register sidebars. Fired at ‘init’ priority 1 (and so before ‘init’ actions with priority ≥ 1!)

So then, based on that information, I changed the init priority to 0:

add_action('init', 'usp_pro_init', 0);

..and then moved the inclusion back into the construct of USP_Pro:

require_once(sprintf("%s/inc/usp-widget.php", dirname(__FILE__)));

..and it works normally.

Take-home lesson

If widget_init is not working when called via init with priority 1, try changing the priority of init to 0.

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress