Posted on

Doing a multisite search

Multisite search only works in Relevanssi Premium.

To search multiple blogs in the same WordPress network, use the `searchblogs` argument. You  can add a hidden input field in the search form, for example. List the desired blog ids as the value. For example, searchblogs=1,2,3 would search blogs 1, 2, and 3.

Here’s an example search form:

<form action="https://www.relevanssi.com/" method="get">
		<input type="text" value="To search, type and hit enter" name="s" id="s" onfocus="if (this.value == 'To search, type and hit enter') {this.value = '';}" onblur="if (this.value == '') {this.value = 'To search, type and hit enter';}" />
</form>

And here’s the same form modified to search blogs 1, 2 and 4:

<form method="get" action="https://www.relevanssi.com/">
		<input type="text" value="To search, type and hit enter" name="s" id="s" onfocus="if (this.value == 'To search, type and hit enter') {this.value = '';}" onblur="if (this.value == '') {this.value = 'To search, type and hit enter';}" />
		<input type="hidden" name="searchblogs" value="1,2,4" />
</form>

The features are very limited in the multiblog search, none of the advanced filtering works, and there’ll probably be fairly serious performance issues if searching common words from multiple blogs. A single search may cause thousands of database calls if the search is made in more than ten blogs, so if your server can’t handle that, there’s going to be trouble. This only affects multisite searches, not single site searches on a multisite installation.

Installing multisite Relevanssi

Relevanssi is a network plugin, so it only needs to be installed once on network level. However, you need to activate the plugin and build the index for each site. On the other hand, you can adjust the settings for each blog.

Changes to search results templates

The search results templates require some changes, otherwise the permalinks will be wrong. Inside the while (have_posts()) loop, add as the second thing after the_post(); this:

<?php switch_to_blog($post->blog_id); ?>

That’ll make sure the blog setting is correct and the permalinks come out right. Make sure you have this code in the right place! I’ve seen couple of cases with problems in the search, caused by having this code in the wrong place. It should be the first thing inside the while loop.

Also, in order to make sure everything else (sidebars, for example) works correctly, you need to restore the current blog. So, as the last thing inside the while loop, add:

<?php restore_current_blog(); ?>

104 comments Doing a multisite search

  1. Hi Mikko, I would like to know a bit more about the multisite install of Relevanssi. You say that on multisite many advanced features are not working. Is that always the case on multisite or only when you want to activate the search over multiple sites?
    I am interested in getting the developer’s license, but if your plugin fails to work properly then I might as well get the normal license.
    Hope you can shed a light on this…

    1. When searching a single blog on a multisite network, all the features of Relevanssi are available. Features go missing only when multiple blogs are searched. Then you lose taxonomy restriction (because the categories, tags and other taxonomies are different on each blog), custom field restrictions, post type restriction (ok, this I could probably add to the multisite search) and synonyms.

      However, the multisite search still searches all the content that regular search does: post content, titles, categories, tags, taxonomies, custom fields, excerpts… You just can’t restrict the search with these extra features.

  2. Thanks for your answer, Mikko.
    So if I understand correctly, there is a separate setting within Relevanssi where you can enable multisite-search with and as long as you don’t enable that setting, all the features of Relevanssi are available. Is this correct?

  3. So I suppose I only need to worry about multisite performance issues if I want to search all the blogs at once? Having Relevanssi installed on all blogs but only doing individual blog searches would surely not be a problem?

  4. Forgive me for being a newbie!

    I’ve gone through and edited the .php for the plugin to add =1,2,3 after the 3 instances of ‘searchblogs’ that I found, saved, and reactivated, but it still doesn’t search across multisite… please tell me what I’m doing wrong to add a hidden input field…

    Just a suggestion, but there might be others that are php newbies that are purchasing the premium plugin just for multisite search – if there was an easier way to activate this, or clearer instructions on what exactly to do ourselves, it would be awesome!

    Thanks so much

    1. You are not supposed to edit the plugin. Using the multisite search requires no PHP coding at all. All you need to do is to add a hidden input field “searchblogs” to your search form, like this: [input type=”hidden” name=”searchblogs” value=”1,2,3″ /] (replace the square brackets with angle brackets). I’ve added an example of this to the post.

  5. Hi, I made a small network of 5 sites, one is populated with content and the other are almost empty. Relevanssi is installed, activated and index is built on all sites.

    I try to run a network search but it seems that only the current site is returning results – it behaves like searchblogs argument does not exist at all.

    I do not have any idea how to continue testing that feature.

  6. Hi Mikko,
    I’m using relevanssi premium developer version, I believe this is the best plugin for improving one of WordPress’ weakest features – search – good work!
    I’m working on getting Multisite search working but currently on appear to get results from only one out of two network sites.
    I have added the necessary hidden field and also the line [switch_to_blog($post->blog_id);] after the while statement. But I don’t have it working yet.
    I read the following comment above “there is a separate setting within Relevanssi where you can enable multisite-search”.
    I can’t see any multisite related options on the setting page under the settings menu. Should I be seeing a Multisite related option to turn on?
    If I’m not missing any options on the settings page i will shared my search template code.
    Thanks,
    Peter

    1. There’s no setting in the options page, it’s talking about the searchblogs query variable. Once you set up Relevanssi as a network plugin, index the contents on each site and make a search using the searchblogs query variable included, it should list results from all blogs. I just tried it on my test system and it seems to work just fine, I’m getting hits from both blogs.

      Could you drop me an email to mikko @ relevanssi.com with more details, so I could take a look at your site?

  7. Hi Mikko,
    I am having a similar issue as Peter where I have installed the plugin on the network, and indexed all the pages that I want it to search (IDs for blogs= 1,61, 96). And my searchform.php looks like this:

    <form action="” id=”searchform” method=”get”>

    However, when you search it only pulls up search results from the main site (ID for blog=1) and not for the other two blogs on the multisite. Another strange thing is that when I created the index for ID 61 and 96 there are no 25 most common words in the index. That may be part of the issue. Can you please help as I am completely stuck?!

    Thanks,
    Marisa

  8. Yeah, WP will strip the code from your comment. Please use something like Pastebin to share the code.

    What the “State of the index” says for the other two blogs? Looks like they weren’t indexed properly for some reason, yes.

  9. Hello,

    Thank you for such an extensive plugin! Just purchased the premium license and I’m running Relevanssi v1.7.2 on a multisite with 4 blogs. After setting it up I can successfully see results from all blogs in the network by searching on the primary website.

    However, Search Hit Highlighting does not work 🙁 Prior to indexing each blog, I was able to add a class to the search highlighting, which worked and displayed correctly in the search results. After indexing each site, the highlighting span does not output in the_excerpt(). Also, the excerpt that outputs does not seem to include the search term. I.e. the_excerpt() is returning the first 450 characters of the post or page in question, then the search term is located around the 600th character.

    Secondly, I added a word, ‘foobar’ to only one blog in the network. When I search, there are results given for blogs without that term. i.e. it seems Relevanssi is returning inaccurate results. This only occurs sometimes.

    Do you have any ideas what I may be doing wrong?

    Thanks!!

  10. Also, for multisite use, I’ve noticed sometimes Relevanssi returns 0 results when there is clearly content to display. I.e. I added the term ‘501’ and ‘Maine’ to the homepage of one blog. However, searching for ‘501’ or ‘Maine’ yields 0 results.

    What am I doing wrong?

    1. Thanks, you’ve found a bug that prevents search highlighting in multisite searches. It’s easy to fix. I’m working on 1.7.3 now, and I’ll include the fix there.

      The excerpt building works as expected for me, so I don’t know what’s wrong on your site. What comes to the foobar thing… again, hard to say, without further debugging. Relevanssi shouldn’t return anything except posts containing the search term. I can’t reproduce the error on my site.

      Hmm, are those missing terms actually indexed? Do they appear in the wp_relevanssi table on the blog they’re in?

      Can you tell me where the site is, I’d like to take a look at it myself? Email me at mikko @ mikkosaari.fi, if you don’t want to mention it in public.

  11. Hi
    I’ve got about 500 blogs on a multisite install. Each blog has 30 posts of about 100 words each. So do you thunk its safe to use your plugin for multisite search on my site?

    I don’t mind experimenting in a backup but am interested in what load I would be expecting to put in the server.

    1. I am having a problem now with the menu getting search results injected into it. Only on certain searches, not all. Have you seen that before?

  12. Sorry Mikko, I had a problem with my search template. After restoring an older version this is working well. Thanks!

  13. Mikko,
    can you clarify the bit about correcting links when searching multiple blogs?
    Where exactly would I paste this?

    Thanks in advance,

    Helen

        1. I added the code right after the while loop statement but it’s not working, search result links are still wrong.

          We have a subdirectory multisite setup, like this:

          http://www.domain.com
          http://www.domain.com/newsroom

          When I search the newsroom site, it does return results from both websites. However, main domain.com articles link to *www.domain.com/newsroom/(article name)*, while it should omit the “newsroom” part from the URL.

          Hope it’s clear? TIA

          1. Well, then it’s not correct. Hard to say, since you showed me such a small snippet from you showed me. Anyway, you did buy the license with no support included, so this is as much as I can help you with this. Make sure the code is inside the main while loop, that’s where it should be, the first thing in there.

  14. If any of you are trying to get the Relevanssi plugin working with the MySite InFocus theme here are the changes we had to make to get it to work in a mulit-site deployment.

    1) in /usr/local/wordpress/wp-content/themes/your_blog/lib/functions/theme.php comment out the 4 occurrences of return query_posts( $query_string ); in function mysite_query_posts(). We had to do this to get the search results on the page

    2) in /usr/local/wordpress/wp-content/themes/your_blog/loop.php add the switch_blog code as mentioned above. we had to remove it from the php tag. the end result looked like this: http://pastebin.com/VdSfgXpc

    3) to override the default search on our site and replace it with a search form that search all of our sites we added /usr/local/wordpress/wp-content/themes/your_blog/searchform.php file that included our custom search form.

    Hope that helps! Many thanks to Mikko for writing such a great plugin and helping us figure this out. Paying for the premium version of the plugin was well worth it and saved us hours of development time.

  15. Would there be a way to use the post indexer plugin so that it doesn’t search accross all blogs but in one table?

    1. Are they two separate installations, or a single multisite installation? If they are two separate installations, Relevanssi can’t search across both. If they are a single multisite installation, the necessary instructions are in this post.

      1. They are 2 separate installations…I guess I misunderstood what ‘multisite’ meant. Do you have any advice for searching on both (is it even possible)? I am a php developer…how hard would it be for me to change the plugin to suit our needs? Should we consolidate the installations? Any thoughts?

        Thanks again,
        JB

        1. Searching both is not possible. Well, I guess it might be possible, but it would be really difficult. I’ve had plans to make Relevanssi index and search things outside of a WP installation, but so far I haven’t figured out how to do it. Getting Relevanssi to use the index of another Relevanssi installation in the same database would be easier, but there are still lots of complications – you’d have to rewrite lots of helper functions to read the other database instead of the current site.

          If you want to search both sites at the same time, the only option at the moment is to make it a single multisite installation (which of course has other problems).

  16. Hello Mikko! I wanna use your search plugin on a language based multisite WP installation (DE/EN). Its activated for both sites. Settings done for both. Indexed for the german version very well. But if I try to build the index for the english version/site the index remains still empty. The settings for both are the same, controlled several times. Do you have any idea for me? Thanks a lot!

    PS: I don’t wanna search over both sides the same time simultaneously.

    best regards
    Dirk

    1. Are you using Premium? If not, it won’t work.

      If you are using Premium, then make sure you’ve done the multisite installation correctly, so that there are separate databases for different sites.

      1. Thanks for your fast feedback Mikko! No, just the basic version. Pity, but now I’ve just certainty. 😉

        best regards
        Dirk

  17. Hi, I bought the premium version, and have spent hours trying to get the switch_to_blog to work properly. Please help!? I have the function right below the while loop. It changes all the urls when I use an integer, but not when a variable is used. So I know the function works. Everything else is working except the correct permalinks. Thanks in advance!

  18. I read everything carefully here about WP multisite installation. But there is one question I couldn’t solve by myself:
    Soon I will have the following situation: I have a WP multisite installation for two different languages of the same site (english and german) and I will buy the premium version of the plugin.

    What kind of script snippets do I need to successfully index both sites when I DON’T want to search over BOTH sites (languages) the same time?

    Do I just need to consider the paragraph “Changes to search results templates”?

    How I understand it your manual above refers to install a cross-multisite search function?

    You see I am little bit lost here 🙂

      1. That’s sounds fantastic! Really great to know. Many thanks for your strong support, Mikko! I really appreciate it. And it’s so good to have your plugin around because it’s so important to have useful search on your website.

  19. Hello!

    I have gotten the search function to automate the whole process of adding blog id:s to the value”1,2,3″ so it automatically searches through all indexed blogs. The script I have added looks into the database and fetches all blog_ids and prints out the ones that exist.

    My question is, when I do a search for the word “dance” i.e. there are several hits on what appears to be links to posts with images and such. These have absolutely nothing to do with the searchword “dance”.

    Any idea why this happens? I have only indexed my main site and one of the blogs. Have to index about 15 more. Could this be a reason?

    Thanks.

    Michael

      1. I wasn’t indexing them, but they had weight. But why are they coming up at all, they have nothing to do with what I’m searching for?

        Ah, now they don’t come up from the blogs that are indexed. But attachments from blogs that aren’t indexed do? Is that because I haven’t indexed them?

        The blogs that I don’t index don’t appear in the search results do they?
        Michael

        1. I’m not sure – Relevanssi should not bring up anything from blogs that haven’t been indexed, but perhaps it’s using wrong database and bringing up posts with IDs that match the query in other databases.

          Anyway, make sure you don’t put unindexed blogs in the searchblogs variable – only list those blogs you actually want to search.

          1. The thing is I have to think about the new blogs being added in the future. I have used this solution to list all blogs that are gonna be created, so it also includes the ones that are testblogs.

            Hence I’ve used the query SELECT blog_id FROM wp_blogs where blog_id >=1 to select all blogs that might be in the blog list.

            I’ve tried to come up with an automated way to exclude blogs 2, 4 and 17 but i’m at a loss how to do it, I’d really appreciate it if you could lead me in the right direction.

            I’ve tried using the sql query to exclude them, but it doesn’t work. I’m doing something wrong.

          2. Well, you can get an array of blog_id’s from the query, keep another array of excluded blogs in a global variable and do an array_diff() between them to get only the non-excluded blog_id’s? Or include the exclusion list in the original MySQL query with “AND blog_id NOT IN ()”?

          3. New question.

            When I go to the second page of the search results my widgets disappear from that page. When I take away the switch_blog code in the while loop they are back. But then my permalinks won’t work as they should.

            /page/2/?s=dansa&searchblogs=1%2C3%2C5%2C6%2C7%2C8%2C9%2C10%2C11

            Where can I fix this issue?

    1. Michael – did you ever find a solution for this? I’m having the exact same issue in a 30+ site multisite installation. I’ve verified that i have an index built on every site in my searchblogs parameter too… What i’ve been finding is that the post_ids of the false-positive results match the post_ids of the correct results but it’s showing an extra entry when that same post_id exists in another blog… Any insight would be appreciated.

      – chuck

        1. Mikko – thanks for the reply. Yes, i am using switch_to_blog() in the search result page template. The more i look into it, i’m pretty sure that the false positive match in question is being returned by the ‘relevanssi_search_multi’ function in relevanssi.php. I have attached a var_dump of that return value (using a search query i know should only return 1 result). The first element in the ‘hits’ array is the one that is incorrect and the pattern i’m finding is that the false-positive matches always have the same post_id so maybe there is something not quite right about the usage of switch_to_blog within relevanssi? I haven’t been able to find it yet but i will continue debugging today. Thanks again.

          For reference, i am running Relevanssi Premium v1.10.13

          – chuck

          1. Mikko – i found the issue and i’ve put a fix in the ‘relevanssi_search_multi’ function to fix it. On line 717 of relevanssi.php, i’ve added a condition to make sure the $matches array is not empty before proceeding so it now looks like: if (isset($doc_weight) && count($doc_weight) > 0 && !empty($matches))

            What seemed to be happening is as it looped through multiple blogs and got to the point where it started retrieving the post_object (line 748), it would populate $post_object if that blog had the same post_id it was looking for regardless of whether there was a match/hit or not. Let me know if you have any questions and hopefully you can add this to the next version.

            – chuck

  20. Hello,

    thanks for this possibility of doing a multisite search.

    What can I do, when I want to give the users the choice of which blog they want to search through?

    At the moment I have a select-field (with multiple attribute). But when choosing two possibilities (out of 4) the URL looks like “/?s=searchterm&searchblogs=1&searchblogs=4”, but it should look like “…&searchblogs=1,4”, shouldn’t it?

    I also tried to make the field an array “”, but then the url looks like “/?s=searchterm&searchblogs%5B%5D=1&searchblogs%5B%5D=4”

    So do you have any idea of how to combine these things, to make a choice possible? Or is their no possibility?
    Thanks in advance!

  21. Here’s what I did: adapted the searchform, activated premium per blog, network activated the plugin, adapted search results template. When searching only the current site gets searched. What am I doing wrong?

  22. How about a restore_current_blog(); just before the endwhile? Some widgets in my sidebar behave very stangely if I don’t restore.

  23. How about a restore_current_blog(); just before the endwhile? Some widgets in my sidebar behave very stangely if I don’t restore.

  24. Hello,

    I am using this plugin for my company. I have the mult-blog search working according to this example. However, on blog 1, it returns 217 results if I search on it. In blog 2, it returns 21.
    HOWEVER: If I search on both at the same time according to this example, I get 21 results from blog 2 and only 6 from blog 1. What’s this about?

    Edit: I also don’t seem to be able to get the score of the blog 1 posts, where as the blog 2 posts return gracefully.

    1. Are you running the latest version of Premium? Earlier versions have some bugs in the multisite search. Otherwise hard to say without taking a look at it; if you have a valid license, send a support request and if you can give me access to your site, I can take a look at it.

      1. Hello again, Mr. Saari.

        Yes, I am running the latest version of premium. After literally hours of debugging it seems to have fixed itself. The reason is absolutely baffling to me.

        After debugging it with a clean wordpress install however, I managed to produce 2 issues. The missing search results issue has been hard to reproduce.

        These steps were taken:
        Clean wordpress install with standard 2016 theme.
        Created multisite.
        Created generic posts on both, and purposefully a few with identical names.
        Added relevanssi and edited my search file etc. for it to work.

        Searching blog 1 works perfectly.
        Searching blog 2 works perfectly.
        Searching blog 1 & 2 breaks score sorting and is missing 3 out of the 4 blog 1 post scores when searching with “searchblog” on ‘1,2’ first. When searching blog “2,1”, the issue would turn around and the scores of 4 out of my 5 blog 2 posts would be missing.

        On my main site the issue fixed itself, but not the score issue. (Altho it does still sort correctly). The $post->revelance_score is simply an empty string on the “other blog”.

        I hope this gives you some insight. For now, it’s not really an issue for us. The real issue is fixed for unknown reasons. (maybe indexing issues?)

        1. Looks like there might be a bug in the code – it seems to me relevance_score is not being set at all in the multisite search. That’s odd; I’ll have to take a closer look at this, but it would certainly explain why it doesn’t appear.

          Can you give me access to the site where you’ve set up the problem to appear? I could take a look at it.

  25. We’re having troubles getting the right permalinks for custom post types. The links are correct for all sites and normal posts, but not custom post type. This has happened out of the blue, we had it working in the beginning.

          1. Hmm… actually, relevanssi_get_permalink() does not really apply there – it only solves cases where the post is a taxonomy term or an user, to make sure the link is correct.

            Is this actually a Relevanssi problem? Do you get the correct permalink without Relevanssi? Relevanssi gets the permalink from get_permalink(), and if get_permalink() is providing a wrong permalink, then what can Relevanssi do?

            Relevanssi doesn’t index the links, it just gets what WordPress provides.

            At least with relevanssi_get_permalink() you can add a filter function on relevanssi_permalink filter hook that corrects the link and adds the “glossary” in the middle of the URL.

          2. We now tried setting up a test environment, and here we can see that /wiki/ redirects to /wiki/glossary/ – works like intended – but on our live environment that redirect does not happen. Is the redirect done by Relevanssi or should I look elsewhere for the problem?

  26. Hi.
    Installed plugin “SearchWP Live Ajax Search”, works perfectly with Relevanssi. But I need on main blog the search results from another blog. Hidden input he does not understand, simply pass a parameter does not work:

    $wp_query->query_vars[‘searchblogs’] = ‘3’;
    relevanssi_do_query($wp_query);

    How can I do this other method?
    Thanks.

  27. If you do not want to add the searchblogs query param to the search form, you can simply add it to the search object after the wp_query and before relevanssi_do_query like so

    $search = new WP_Query( array(
    ‘s’=> $qv,
    ‘posts_per_page’=> 30,
    ‘paged’ => $paged,
    ));

    $search->query_vars[‘searchblogs’] = ‘1,7,8,9,16,18’;

    relevanssi_do_query($search);

  28. We’re using Relevanssi on our multisite network and it is working really well! Thanks for that! But we now want to have a pretty URLs instead of: /?s=html&searchblogs=1%2C3%2C10%2C5%2C6%2C7%2C9%2C11
    Is it somehow possible to hide all the blog IDs while keeping the functionality?

        1. add_filter(‘pre_get_posts’, ‘rlv_add_searchblogs’);
          function rlv_add_searchblogs($query) {
          $query->set(“searchblogs”, “1,3,10,5,6,7,9,11”);
          }

          Something like that.

  29. The WordPress core function “get_permalink” returns a URL with the current site’s domain even if it is from another blog. I included the switch_to_blog function as I should but the search results template returned by “get_template_part” is where the “get_permalink” function is executed. Any suggestions?

      1. No it doesn’t.
        while ( have_posts() ) :
        switch_to_blog($post->blog_id);
        the_post();
        echo the_permalink(); // always a domain for the site the search page is on, not the domain for the site whose id is $post->blog_id.
        restore_current_blog();
        endwhile;

  30. Hi Mikko

    I am considering purchasing the premium version of the plugin.
    I have a multisite intalled. All sites have the same taxonomies – will they still not be indexed properly?

    Many thanks

    1. Rebecca, the taxonomies will be indexed as usual. You just can’t filter multisite searches using the taxonomies, even if the taxonomies match between sites – they’re still different taxonomies, even if they have the same names. You can use taxonomy filters in single site searches.

Leave a Reply

Your email address will not be published. Required fields are marked *