Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?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

This comment has been minimized.

Copy link

@joshzee 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