wp query - In a WordPress multisite configuration, how do I instruct WP_Query() to return posts from a sub-site?

admin2025-06-06  2

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:

  • 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:

  • How would I use pre_get_posts to query another site for posts in my multisite network?
  • Querying Posts by Taxonomy From Alternate Network Site
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749142087a316723.html

最新回复(0)