Skip to content
Advertisement

Programmatically inserting a widget into WordPress sidebar

I have been using this code on PHP 7.0, but decided to upgrade to 7.4 tonight. This code automatically inserts widgets into WordPress sidebar, but it no longer works.

function insert_widget_in_sidebar( $widget_id, $widget_data, $sidebar ) {
// Retrieve sidebars, widgets and their instances
$sidebars_widgets = get_option( 'sidebars_widgets', array() );
$widget_instances = get_option( 'widget_' . $widget_id, array() );

// Retrieve the key of the next widget instance
$numeric_keys = array_filter( array_keys( $widget_instances ), 'is_int' );
$next_key = $numeric_keys ? max( $numeric_keys ) + 1 : 2;

// Add this widget to the sidebar
if ( ! isset( $sidebars_widgets[ $sidebar ] ) ) {
    $sidebars_widgets[ $sidebar ] = array();
}
$sidebars_widgets[ $sidebar ][] = $widget_id . '-' . $next_key;

// Add the new widget instance
$widget_instances[ $next_key ] = $widget_data;

// Store updated sidebars, widgets and their instances
update_option( 'sidebars_widgets', $sidebars_widgets );
update_option( 'widget_' . $widget_id, $widget_instances );
}

From my research, it seems to be a problem with “[]” not initializing arrays anymore.

I’ve tried every single way I know how, but can’t get this to work. I’ve always initialized arrays with [], so I’m sort of lost.

This is an example of the input data:

insert_widget_in_sidebar('recent-posts',array('title' => $recent_posts_title,'number' => $recent_posts_number,'show_date' => $show_date),$sidebar_name);

Where $sidebar_name would be, for example, ‘right-sidebar’.

Advertisement

Answer

I was finally able to solve the problem by properly initializing the arrays… this is an edited version of the code made for my purposes, but here are the main changes:

if ( !isset( $sidebars_widgets[$sidebar] ) ) {
    $sidebars_widgets = array();
    $sidebars_widgets[$sidebar] = array();
}
$sidebars_widgets[$sidebar][] = $widget_id . '-' . '1';

// Add the new widget instance
$widget_instances = array();
$widget_instances[1] = $widget_data;
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement