Home » Wordpress » Is there a way to programatically enable a widget from a plugin in WordPress?

Is there a way to programatically enable a widget from a plugin in WordPress?

Posted by: admin November 30, 2017 Leave a comment

Questions:

I’ve got a plugin I wrote for wordpress and I need to have the Pages widget enabled for everything to work properly. It would be nice if I could enable it myself in the plugin rather than requesting the user to do this.

Do you know of a way to do that?

Answers:

Not exactly sure how your widget works, but you could auto enable the pages widget by adding it to the options table, but you’d have to add code to be able to read the widget storage type and then decide if the Pages widget is available in the correct sidebar (you don’t say if the widget has to be enabled within the same sidebar within the theme, but I’m guessing that it does). Then you also have to figure out where to position the pages widget relative to the others in the sidebar, since position is something the wp admin usually does on the widget admin tool.

That said, I think your best bet is to get your widget to either raise an error or fail quietly if it doesn’t have what it needs to be successful at run time. You should be able to add text to the widget config that displays a message about the pages widget dependency in the admin widget tool. Whether or not this can easily be done dynamically, I haven’t really researched.