Created
August 24, 2016 10:43
-
-
Save tyxla/372f51ea1340e5e643f6b47e2ddf43f2 to your computer and use it in GitHub Desktop.
Insert a widget in a sidebar programmatically in WordPress
Nice, thanks @hkujla!
Thank you. I've probably been trying to figure this out for a year.
@hkujla , what is $new anyway? thanks
Sadly this code no longer works in php 7.4, any way to get an update @tyxla?
Happy to update it @seowner! Could you share some more information about the error you are getting on PHP 7.4?
@tyxla I was able to fix it (to meet my own specifications) by doing this:
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;
It seems the main problem was PHP 7.4 will not allow you to use [] to initialize arrays without first initializing them with array().
Although this code isn't the same as yours above, I hope it makes things faster for you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You saved my day, Perfect solution. Thanks. I would like to share to avoid widget duplication.
if (!is_active_widget( false, $widget-id, $obj->id_base, true ) ) {
insert_widget_in_sidebar( $widget_id, $widget_data, $sidebar );
} else {
widget_update_by_subsite($widget_id,$new);
}
function widget_update_by_subsite($widget_id,$new) {