I’m trying to find away to retrive a dynamic sidebar from one blog and print it on another blog in the same install of WordPress Multisite. I have tried
switch_to_blog($blog_id);
dynamic_sidebar($sidebar_name);
restore_current_blog();
But nothing is returned.
I also tired to retrive the sidebar through get_blog_option($blog_id, 'sidebar_widgets')
but I was only able to retrive an array identify what widgets were used by the sidebar, but I couldn’t find away to process the array into a sidebar.
5 s
Unfortunately, the switch_to_blog()
method isn’t going to work for this purpose. switch_to_blog()
is really only a partial switch – it makes some modifications to $wpdb
that help with database queries. But it’s not a complete switch in the way you might imagine.
In particular, dynamic_sidebar()
depends on global called $wp_registered_sidebars
. This global is populated by register_sidebar()
, which is generally called from a theme file like functions.php. But functions.php, and the rest of the theme setup process, is not re-run by switch_to_blog()
. That is to say: if you’re running Twenty Eleven on the current blog, it’ll register its own sidebars during startup; using switch_to_blog()
to a blog running Twenty Ten will not tell Twenty Ten to set up its sidebars. You could try forcing it (by loading the switched-blog’s functions.php manually) but this is almost certain to lead to disaster, due to issues with duplicate function names, load order, etc etc etc.
You might try a somewhat different tack: On the blog with the sidebar that you want, build a function that will print the contents of the sidebar into the output buffer, and then before printing it to the screen, stash it in a site_option. Then you can grab the sidebar (or a static version of it, at least) from any site on the network. This won’t work if you absolutely need a totally dynamic sidebar, but for most purposes you probably don’t.
Another method (which may be easier) is to render the sidebar with a function in an mu-plugins file or something like that, and then call the function manually in your themes (or hook it to a common sidebar hook). It might take some work to abstract the content out of the WP_Widget
architecture, but on the other hand it would be a truly dynamic solution to the problem at hand.