2

I am trying to retrieve search results from one multi-site site ("Staffsite" - id: 2) and display them alongside the search results on another site that's part of the multi-site setup ("Flagship" - id: 1). I currently have the following code in search.php on Flagship:

$args = array(
    'post_type' => 'staff',
    's'         => get_search_query(),
);

switch_to_blog( 2 ); // switch to Staffsite

$staffsite_query = new WP_Query( $args );

var_dump( $staffsite_query->post_count ); // 0

// Do something with post data

restore_current_blog(); // return to Flagship

The query works as expected when used in a template on Staffsite (replacing get_search_query() with an actual value), returning all the relevant posts, but does not work when used from a template on Flagship in combination with switch_to_blog().

For what reason does this not work?

  • It doesn't look like there's a switch_to_network() that's the equivalent of switch_to_blog(). You might find what you need in the WP Multi Network plugin. – Pat J Sep 3 '18 at 16:19
  • 1
    @PatJ apologies, wrong terminology on my part. The sites are part of a multisite setup, not a multi-network setup. – Sillzen Sep 4 '18 at 8:14
  • Is the staff post type defined in a plugin? If so, and the plugin is only activated on blog 2, then its code won't be loaded on a request for blog 1, even when you use switch_to_blog, so it won't recognize the post type in the query. – Corey McKrill Sep 5 '18 at 0:00
2

Alternative option could be using the Rest API:

Example (post):

Search for Jane Doe in posts:

https://example.com/staffsite/wp-json/wp/v2/posts/?search=jane+doe

Example (custom post types):

If the public and searchable custom post type (e.g. staff) has show_in_rest set to true then we can search for Jane Doe in staff posts:

https://example.com/staffsite/wp-json/wp/v2/staff/?search=jane+doe

ps: Somewhat related, if you want to create your own route, using data from multiple sites in the network: WP REST API - Multisite - get posts from all sites

|improve this answer|||||

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.