Skip to content

Snippet: Query Items From Different Blogs on a Multisite

In WordPress there is no way to use the core WP_Query class to pull items from different multisite installations. For this reason if you want to insert a Total module on a multisite that queries items from a different site you need to hook into the vcex_shortcode_before and vcex_shortcode_after action hooks and use the switch_to_blog function in WordPress to switch databases. The example below demonstrates how to do this. Note how we are applying the tweaks to the "vcex_recent_news" shortcode (Recent News module) and only if that module has the "main_blog_recent_news" unique_id attribute this way we aren't applying the switch_to_blog function to all modules but only the specific one we are trying to target (see the screenshot).

add_action( 'vcex_shortcode_before', function( $shortcode, $atts ) {
	if ( 'vcex_recent_news' === $shortcode && isset( $atts['unique_id'] ) && 'main_blog_recent_news' == $atts['unique_id'] ) {
		switch_to_blog(1);
	}
}, 10, 2 );

add_action( 'vcex_shortcode_after', function( $shortcode, $atts ) {
	if ( 'vcex_recent_news' === $shortcode && isset( $atts['unique_id'] ) && 'main_blog_recent_news' == $atts['unique_id'] ) {
		restore_current_blog();
	}
}, 10, 2 );
All PHP snippets should be added via child theme's functions.php file or via a plugin. We recommend Code Snippets (100% Free) or WPCode (sponsored)
Back To Top