[wp-hackers] Programmatic Widget Handling

Peter Westwood peter.westwood at ftwr.co.uk
Tue Oct 19 09:04:17 UTC 2010

Hi Martin,

On 19 Oct 2010, at 07:31, Martin Widmann wrote:

> I'm currently working on an extension to the widget's functionality to allow users of the site to create virtually unlimited amounts of new sidebars, filter them and add widgets to them. As long as it's sidebars it's pretty straight forward. 
> - register Sidebar
> - Store sidebar settings in options
> - when init fires, re-create the stored sidebars 
> Having many sidebars in many configurations calls for an import/export functionality. And this is where it gets tricky. I haven't found a good way of adding/removing widgets programmatically. It all seems to get done via rewriting parameters in the POST and than calling back various methods on WP_Widget. Trying to reverse engineer this functionality added the widgets to the database in some "invisible" space, but not to the sidebar I wanted.
> Therefore I decided to go the hard way and do the operations on the simple serialized arrays stored in the database:
> - sidebars can either be overwritten or not if they exist on destination
> - check if all the widgets used on the sidebar to import are available on the destination
> - reset the sidebar's widgets in $sidebars_widgets - I'm not going to delete the old widgets as I fear this could turn out in a mess
> - iterate over the new to assign widgets. The numeric value that identifies the instance is get from an internal array that initializes with the value of $wp_widget_factory->widget[ $widget_class ]->number and then gets incremented internally.
> - push the widget's settings into the unserialized value of option widget_$id_base also gotten from $wp_widget_factory and update the option.
> - once all widgets for the sidebar are done, I update the sidebars_widgets option and go over to the next sidebar.
> I'm not sure if I covered all ends and if there's a simpler way of doing this. I also fear that this solution might break in a future version of WordPress. What do you think?

It sounds like what you need is a comprehensive widget management api!

The best way to get this is to work through the current widget code in wp-admin/widgets.php and try and abstract it out into an api which that code can use and your plugin can use.

Submit this as a core patch and once it is included you will have an api to base your plugin on.

Peter Westwood
http://blog.ftwr.co.uk | http://westi.wordpress.com
C53C F8FC 8796 8508 88D6 C950 54F4 5DCD A834 01C5

More information about the wp-hackers mailing list