0

I have a WordPress multisite with one main site and four sub-sites. All five sites have a custom post type with the name property, and each site has several posts of this type. In a PHP template on my main site, I would like to execute a WP_Query() that fetches all of these custom posts from one of the sub-sites (id = 4). How would I approach that?

My existing code is:

$blog_id = 4;
$posts = array();
switch_to_blog( $blog_id );
$query = new WP_Query(
  array(
    'post_type' => 'property',
  )
);
while ( $query->have_posts() ) {
  $query->next_post();
  $posts[] = $query->post;
}
restore_current_blog();
error_log(print_r($posts,true));

The output written to the error log is a zero-length array:

[29-Nov-2018 11:33:44 UTC] Array
(
)
  • I have confirmed that $blog_id = 4 does indeed contain several posts of type property.

Previous Stack Exchange Questions

I found these three related questions, but none have a marked answer:

I found these two questions with workarounds marked as the answer, and the scope of the first is dissimilar to mine. I'd like to know if a solution exists before pursuing a workaround:

4
  • 1
    What exactly is the problem with switch_to_blog() & restore_current_blog() as suggested in the linked questions?
    – kero
    Commented Nov 29, 2018 at 12:16
  • @kero Which question do you mean?
    – cag8f
    Commented Nov 29, 2018 at 16:13
  • This answer uses the method, but has alot of code. They reference this answer which suggest switch_to_blog( ID ); /* do your stuff */ restore_current_blog(); for this kind of work
    – kero
    Commented Nov 29, 2018 at 16:33
  • @kero Doesn't my code also follow the switch_to_blog( ID ); /* do your stuff */ restore_current_blog(); model?
    – cag8f
    Commented Nov 30, 2018 at 11:50

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.