A while ago, I wrote about how to preset widgets to widget areas (sidebars) in themes, but that method doesn’t work anymore with the new multi-widget implementation. Here’s the new way:
Step 1: Add a new instance of the widget to the options table
update_option( 'widget_search', array( 2 => array( 'title' => '' ), '_multiwidget' => 1 ) );
Parameters:
- Prefix
widget_with the id base of the Widget’s class. - A two-dimensional array with:
- the first array containing the widget’s settings
- and the second containing the required:
'_multiwidget' => 1
Note: In the second parameter of update_option, I gave the array a key value of 2. This number is intentionally there. More on that in step 2.
Do as many of those update_option calls for each widget instance you’d like to register. Then move along to step two:
Step 2: Update the sidebars options table
update_option( 'sidebars_widgets', array( 'sidebar-1' => array( 'search-2', ), 'wp_inactive_widgets' => array(), 'array_version' => 3 ));
The only thing you have to change here is the array in the second parameter:
- The array keys should be the id of the widget area
- And it’s values should be the id base of the widget’s class, a dash, and then the same number we used as a key for the widget (created in step 1). In this case, it’s 2.
You may optionally preset widgets as inactive by throwing them in the wp_inactive_widgets array. And I wouldn’t mess with the array_version array. This is a hack since we’re not using any proper APIs to preset widgets so don’t go messing around with too much.
Et volia! You just perform the equivalent of selecting a widget from the available widgets section, dragging that instance over to a widget area, configured it, and saved the changes.. all through code!
Here’s the complete code along with additional sidebars and widgets so you see how that looks.
Round 2: Preset widgets to widget areas http://tinyurl.com/y8cd4y2
This comment was originally posted on Twitter
Ptah Dunbar: Round 2: Preset Widgets to Widget Areas http://goo.gl/fb/VTnM
This comment was originally posted on Twitter
Preset Widgets to Widget Areas – Ptah Dunbar http://ff.im/-fTdra
This comment was originally posted on Twitter
This works as advertised, thanks much.
I have a problem with this, however. If a widget is inserted after having been registered using the update_option, that widget cannot be inserted again manually.
Case in point, I have a breadcrumb widget that I’m inserting by default upon theme activation. Works fine.
When I insert another copy of that widget, let’s say I want it above my body content again — the widget is saved in the backend but not shown in the frontend.
Any tips?
I managed to fix this. Obviously the update_option() calls should only be run on activation, and not every time.