Re: Sharing Sidebars Across a Multisite Network

In a post yesterday at WebDevStudios about “Sharing Sidebars Across a Multisite Network”, I was reminded of a workaround that I had to put into the Widget Customizer plugin. There is this unfortunate condition inside of the core wp_get_sidebars_widgets() function:

// If loading from front page, consult $_wp_sidebars_widgets rather than options
// to see if wp_convert_widget_settings() has made manipulations in memory.
if ( !is_admin() ) {
    if ( empty($_wp_sidebars_widgets) )
        $_wp_sidebars_widgets = get_option('sidebars_widgets', array());
    $sidebars_widgets = $_wp_sidebars_widgets;
} else {
    $sidebars_widgets = get_option('sidebars_widgets', array());

So you can see here that if wp_get_sidebars_widgets() gets called early (and it does) then the initial value returned will persist even if the underlying sidebars_widgets option changes (or is filtered); after this function is called on the site frontend, the returned value will persist in that private global variable $_wp_sidebars_widgets.

This was a problem for Widget Customizer because it needed to be able to override the sidebars’ widgets on the fly within the customizer preview. Fortunately, the return value of wp_get_sidebars_widgets() is filterable via the sidebars_widgets hook, and so this is what we did to get around the above behavior:

add_filter( 'sidebars_widgets', function ( $sidebars_widgets ) {
    $sidebars_widgets = get_option( 'sidebars_widgets' );
    unset( $sidebars_widgets['array_version'] );
    return $sidebars_widgets;
} );

Would this workaround also allow switch_to_blog() to be able to render sidebars from other blogs on the network?

Leave a Reply

Your email address will not be published. Required fields are marked *