Skip to content

Instantly share code, notes, and snippets.

@lucasstark
Last active March 9, 2021 02:42
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucasstark/132511ab333f0c5fb6c4e82458ba2d20 to your computer and use it in GitHub Desktop.
Save lucasstark/132511ab333f0c5fb6c4e82458ba2d20 to your computer and use it in GitHub Desktop.
<?php
add_action( 'template_redirect', 'wp_multisite_sidebar_save' );
function wp_multisite_sidebar_save() {
if ( is_main_site() && isset( $_GET['get_sidebar'] ) ) {
$sidebar = $_GET['get_sidebar'];
ob_start();
dynamic_sidebar( $sidebar );
$markup = ob_get_clean();
set_site_transient( 'sidebar_cache_' . $sidebar, $markup, HOUR_IN_SECONDS );
die();
}
}
function wp_multisite_sidebar( $sidebar ) {
$markup = get_site_transient( 'sidebar_cache_' . $sidebar );
if (!is_main_site() && $markup ) {
echo $markup;
} else {
if (!is_main_site()) {
wp_remote_get( add_query_arg( array('get_sidebar' => $sidebar), get_site_url( 1 ) ) );
echo get_site_transient( 'sidebar_cache_' . $sidebar );
} else {
ob_start();
dynamic_sidebar($sidebar);
$markup = ob_get_clean();
set_site_transient( 'sidebar_cache_' . $sidebar, $markup, HOUR_IN_SECONDS );
echo $markup;
}
}
}
add_action( 'sidebar_admin_setup', 'wp_multisite_sidebar_clear_cache' );
function wp_multisite_sidebar_clear_cache() {
global $wp_registered_sidebars;
foreach($wp_registered_sidebars as $sidebar){
delete_site_transient('sidebar_cache_' . $sidebar['id']);
}
}
@joshzee
Copy link

joshzee commented Mar 9, 2021

Hi Lucas,

I've been looking at ways to implement a multisite constant piece of information.
This seems to be it and has been implemented a little differently by Red Tree (they've given you credit and how I got here).

The one thing I can't quite figure out is where I place this code..?
In the functions.php after registering my sidebars, in this case how does WPMS know what the variable $sidebar is?

Or is this a separate sidebar file that needs to registered?

Thank you for sharing and your knowledge on this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment