Snippets: Query Items in Total Modules From Different Blogs on 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 );

Result:

Version Required:4.9.9.3+

Snippet Type: PHP

All PHP snippets should be added via a child theme's functions.php file.