[wp-hackers] Programmatic Widget Handling
Martin.Widmann at medienhaus.com
Tue Oct 19 06:31:48 UTC 2010
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?
More information about the wp-hackers