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 typeproperty
.
Previous Stack Exchange Questions
I found these three related questions, but none have a marked answer:
- Get posts from the Main site to sub site - Wordpress MultiSites Network
- WP_Query on different site in a multisite setup
- Multisite wp_query & switch_to_blog issue
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:
switch_to_blog()
&restore_current_blog()
as suggested in the linked questions?switch_to_blog( ID ); /* do your stuff */ restore_current_blog();
for this kind of workswitch_to_blog( ID ); /* do your stuff */ restore_current_blog();
model?