Skip to content

Instantly share code, notes, and snippets.

@moyarich
Created February 10, 2015 21:08
Show Gist options
  • Select an option

  • Save moyarich/59471494a38c4d5d7073 to your computer and use it in GitHub Desktop.

Select an option

Save moyarich/59471494a38c4d5d7073 to your computer and use it in GitHub Desktop.
Programmatically add wordpress widgets to specific sidebars
/**
* Programmatically add widgets to sidebars
* @param array $add_to_sidebar an array with the name of the sidebar and the widget instance information
* $sidebar_id = 'primary-widget-area';
* $add_to_sidebar[$sidebar_id] = array(
* array(
* 'id_base'=> 'archives',
* 'instance' => array(
* 'title' => 'Archived Content',
* 'dropdown' => 'on',
* 'count' => 'on',
* )
* ),
*
* array(
* 'id_base'=> 'search',
* 'instance' => array(
* 'title' => 'Search My Site',
* )
* ),
* array(
* 'id_base'=> 'meta',
* 'instance' => array(
* )
* )
* );
*
* @param boolean $ignore_sidebar_with_content if true, will not add widgets to a sidebar that already has widgets, Default true
*
*/
function auto_add_sidebar_widgets( $add_to_sidebar = array(), $ignore_sidebar_with_content = true ){
if(empty($add_to_sidebar)){
return;
}
$sidebar_options = get_option('sidebars_widgets');
foreach($add_to_sidebar as $sidebar_id => $widgets){
//** do not add widgets if sidebar already has content
if ( ! empty( $sidebar_options[$sidebar_id] ) && $ignore_sidebar_with_content) {
continue;
}
foreach ($widgets as $index => $widget){
$widget_id_base = $widget['id_base'];
$widget_instance = $widget['instance'];
$widget_instances = get_option('widget_'.$widget_id_base);
if(!is_array($widget_instances)){
$widget_instances = array();
}
$count = count($widget_instances)+1;
$sidebar_options[$sidebar_id][] = $widget_id_base.'-'.$count;
$widget_instances[$count] = $widget_instance;
//** save widget options
update_option('widget_'.$widget_id_base,$widget_instances);
}
}
//** save sidebar options:
update_option('sidebars_widgets',$sidebar_options);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment