create the function code required to add WordPress multisite search

WordPress AI Code Robot

Create WordPress code snippets for free without a developer!

{Name (First):7.3} requested the  following code from my WordPress AI Code Generator.

create the function code required to add WordPress multisite search

The robot generated the following code:

Creating a function to add a multisite search in WordPress requires the use of multiple functions and WordPress hooks. Here is a simple approach to create a function that uses the "switch_to_blog" and "restore_current_blog" functions.

Please, note that the 'nm_create_' prefix has been applied to function names for the sake of clarity and uniqueness of the code in your WordPress project.

“`php
function nm_create_multisite_search($query) {
if (!is_admin() && $query->is_main_query() && $query->is_search()) {
global $wpdb;
$blogs = $wpdb->get_results($wpdb->prepare("SELECT blog_id FROM {$wpdb->blogs} WHERE site_id = %d AND public = '1' AND archived = '0' AND mature = '0' AND spam = '0' AND deleted = '0'", $wpdb->siteid));
$search_results = array();
$search_query = $query->query_vars['s'];
foreach ($blogs as $blog) {
switch_to_blog($blog->blog_id);
$args = array(
's' => $search_query,
'post_type' => 'any'
);
$multisite_query = new WP_Query($args);
if ($multisite_query->have_posts()) {
while ($multisite_query->have_posts()) {
$multisite_query->the_post();
$search_results[] = array(
'blog_id' => $blog->blog_id,
'post_title' => get_the_title(),
'permalink' => get_permalink(),
'post_excerpt' => get_the_excerpt(),
'post_date' => get_the_date()
);
}
}
restore_current_blog();
}
return $search_results;
}
}

add_action('pre_get_posts', 'nm_create_multisite_search');
“`

This `nm_create_multisite_search()` function will run before the query is done when a search query is made on the WordPress multisite. It creates and loops through a new WordPress query for every blog on the WordPress multisite. When it finds posts related to the query, it stores them in a `search_results` array and returns them.

More
CODE SNIPPETS