This is a custom version of WP_Query_Multisite, by ericandrewlewis, to support multisite post queries but without changing the class declaration, we will use the good ol' WP_Query
. Just by entering the custom query var multisite => true
on your query args and your query is now global.
$query = new WP_Query( [ 'multisite' => true ] );
while($query->have_posts()) {
$query->the_post();
switch_to_blog( $post->site_ID );
echo $blog_id . get_the_title() . '<br>';
restore_current_blog();
}
wp_reset_postdata();
To modify what sites are queried, create a 'sites' element in the $args in the constructor parameter, with a sub-element of either 'sites__in' or 'sites__not_in', which will be an array similar to 'posts__in' in the WP_Query object.
$args = [
'multisite' => 1,
'sites__in' => [ 1, 2, 3, 5 ]
];
$query = new WP_Query( $args );
while($query->have_posts()) {
$query->the_post();
switch_to_blog( $post->site_ID );
echo $blog_id . get_the_title() . '<br>';
restore_current_blog();
}
wp_reset_postdata();
On your functions.php:
add_action('pre_get_posts', function ($query) {
if( !is_admin() && $query->is_main_query() && $query->is_search() ) {
$query->set('multisite', true);
}
});