How can I search across multiple sites in a multi-site?
For multi-site (aka Network Mode) installations of WordPress, ElasticPress offers the custom site__in WP_Query parameter. This parameter lets you specify a number of different options to search across one or multiple sites in the network.
The site__in parameter takes a few different options, including current, all, and an array of Site IDs like [ 2, 3 ].
For example, if you want to make all your searches display results from all your sites:
add_action(
'pre_get_posts',
function ( $query ) {
if ( is_admin() || ! $query->is_main_query() || ! $query->is_search() ) {
return;
}
$query->set( 'site__in', 'all' );
}
);
As another example, if you want to search just the current site, simply add the following to your WP_Query:
new WP_Query(
[
's' => 'search phrase',
'site__in' => 'current',
]
);
Want results from all sites on the network? Just adjust the query to change site__in to all:
new WP_Query(
[
's' => 'search phrase',
'site__in' => 'all',
]
);
And if you need results from just a few of the sites on your network, you can specify them using their numeric Site IDs:
new WP_Query(
[
's' => 'search phrase',
'site__in' => [ 2, 4 ],
]
);
Autosuggest
If you want to display results from different sites in Autosuggest, you’ll need to change the URL used for the Autosuggest request. You can use the ep_autosuggest_options
filter to change Autosuggest’s endpointUrl
parameter:
add_filter(
'ep_autosuggest_options',
function ( $epas_options ) {
if ( ! \ElasticPress\Utils\is_epio() ) {
return $epas_options;
}
$host = \ElasticPress\Utils\get_host();
$endpoint_url = trailingslashit( $host ) .
\ElasticPress\Indexables::factory()->get( 'post' )->get_network_alias() .
'/autosuggest';
$epas_options['endpointUrl'] = esc_url( untrailingslashit( $endpoint_url ) );
return $epas_options;
}
);