WordPress Code Snippets

A fresh mix of code snippets and tutorials

WordPress widget_init not working

257

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:

..and then in the USP_Pro class:

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

..which includes the widget class:

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:

..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

WordPress Themes In Depth


Show Support

Like our new Facebook Page to show support!