1

So I have a Primary site that posts announcements about the sub sites, for each of those posts I have a meta value that the user sets for which site those announcements apply too. On each of those sub sites, I'd like to include those announcements for that site in the regular post loop.

So far I've only been able to display them separately

$latest_posts = get_posts( array(
  'numberposts' => 5
) );

switch_to_blog('1');

$networkPosts = get_posts( array(
  'posts_per_page' => 5,
  'date_query' => array(
    'after' => date('Y-m-d', strtotime('-1130 days'))
  ),
  'meta_query' => array(
    array(
      'key' => 'shows',
      'value' => $id,
      'compare'   => 'LIKE',
    )
  )
));

Tried merging the networkPosts query with the regular query using Pre_Get_Posts, but it was a mess.

function add_network_to_query( $query ) {
  if ( $query->is_home() && $query->is_main_query() ) {
    $id = get_current_blog_id();
    switch_to_blog('1');
    $networkPosts = get_posts( array(
      'posts_per_page' => 0,
      'date_query' => array(
        'after' => date('Y-m-d', strtotime('-1130 days'))
      ),
      'meta_query' => array(
        array(
          'key' => 'shows',
          'value' => $id,
          'compare'   => 'LIKE',
        )
      )
    ));
    restore_current_blog();
    $query = array_merge($query, $networkPosts );
  }
}
add_action( 'pre_get_posts', 'add_network_to_query' );

TLDR; I want to include the posts from Site 1 with a certain meta value, into my query for each individual sub site.

-1

If you want to work with it just like with WP_Query, you can use this construction.

$query = new Network_Query( array( 
    'blog_id' => array( 1, get_current_blog_id() ),
    'posts_per_page' => 5,
    'date_query' => array(
       'after' => date('Y-m-d', strtotime('-1130 days'))
    ),
   'meta_query' => array(
       array(
          'key' => 'shows',
          'value' => $id,
          'compare'   => 'LIKE',
       )
    )
) );

if( $query->have_posts() ) :

    while( $query->have_posts() ) : $query->the_post();


    endwhile;

endif;

So, we merged the current blog and the blog with ID1 into a single loop.

To make the Network_Query work on your website, additional plugin is required https://rudrastyh.com/plugins/get-posts-from-all-blogs-in-multisite-network

Hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.