Round 2: Preset Widgets to Widget Areas

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.

3 Tweets

3 Comments

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Additional comments powered by BackType

About Ptah

I’m a 21 year old web developer, entrepreneur, and founder of Design by Craftsmen, web creative studio specializing in custom WordPress solutions. Get to know me.

Twitter