Direct access to the query engine

Relevanssi can’t be used in any situation, because it checks the presence of search with the is_search() function. This causes some unfortunate limitations and reduces the general usability of the plugin.

You can, however, access the query engine directly. There’s a function called relevanssi_do_query(), which can be used to do search queries just about anywhere. The function takes a WP_Query object as a parameter, so you need to store all the search parameters in the object (for example, put the search terms in $your_query_object->query_vars['s']). Then just pass the WP_Query object to Relevanssi with

relevanssi_do_query($your_query_object);.

Relevanssi will process the query and insert the found posts as $your_query_object->posts. The query object is passed as reference and modified directly, so there’s no return value. The posts array will contain all results that are found.

  • Andrei

    I suggest that you add this note to your installation notes on the plugin page. Something like “If you develop your own search form, use this function to access Relevanssi directly”.

    It would have saved me at least an hour 🙂 Otherwise, great work!

  • cirkut

    I’m just wondering. When you say to pass the search terms into the query object, is there any additional step that needs to be done rather than `$search = new WP_Query($search_query);`? `$search_query` has `’s’` set, so do I just call `relevanssi_do_query($search)`?

    • Yes, that should work.

      • Chris

        It doesn’t work. I am doing a custom AJAX search and I can’t get any results with your plugin. Can you please post a complete example on how to query the engine?

        [code]
        $your_query_object->query_vars['s'];
        relevanssi_do_query($your_wp_query_object);
        print_r($your_query_object);
        [/code]

        $your_query_object->query_vars[‘s’]; does not read the querystring. I have tried with other strings, but with the same result.

        $wp_query does not contain anything for posts, query or s either.

        • Do note the example has a mistake in the variable names, it’s $your_query_object in one place and $your_wp_query_object in another. It should be the same everywhere.

          I don’t have a complete example ready, as I don’t use this feature on any of my blogs.

          • Chris

            Yeah sorry for the variable names, they should be the same. Nevertheless, it’s not working and I don’t know why. Only thing I have ever managed to get is errors from the relevanssi.php file.

        • Erwin

          Late reply, for future reference: Chris, I think the issue is the fact that you’re doing an custom AJAX search here, and not a particular problem with Relevanssi. You’re calling a PHP file directly – but that means that nothing WordPress is loaded in that file.

          My suggestion: create your AJAX search php file as a custom template, assign this template to a post and then call the post URL rather than the php file directly. Your PHP file doesn’t need to contain anything extra, but since it’s loaded through WordPress will contain all the necessary functionality.

  • wp_fish

    I’ve created a wordpress site but have added my own table which also has a title and description field. Is it possible to include this new table in the search results?

    • No, that’s not possible (not yet, at least).

  • @Chris, if you do have a license that includes support, drop me an email at mikko@relevanssi.com and show me the complete code and I’ll take a look at it.

  • Morten

    Hi

    I manage to use you relevanssi_do_query to only search in my custom post, but you do not use the result of the Wp_Query in your search just some of the query variables ?

    I would like to use the meta_query to only search for some key values. Is this possible in the licensed version ?

    • Please explain in more detail what you want to do, I don’t quite understand what you’re after here.

  • Dmitry

    Hi,
    how about presswork + relevanssi? Doesn’t work for me…
    In readme file there is very poorly explained how get relevanssi to work…

    I use this piece of code for my search form:

    if(!function_exists(‘pw_html5_search_form’)) :
    function pw_html5_search_form( $form = false ) {
    $form = ‘
    ‘ . __(‘Search for:’, “presswork”) . ‘

    ‘;

    return $form;
    }
    endif;

    Note: home_url( ‘/’ ) . ‘search
    I tried with search page and post types. Bot aren’t working…
    Any ideas?

    Best regards.

    • I’ve never even heard of PressWork, so hard to say… What does it even do?

      • Dmitry

        Yeah, it’s a theme engine.
        Pretty good one: http://presswork.me
        I use it nowadays in every project.

        In my child theme is something like this (inside of index.php):
        ID, ‘pw_single_layout’, true);
        if($fullwidth==2) $layout = “maincontent”;
        }
        $layout = explode(“,”, $layout);
        $i = 1;
        foreach($layout as $elem) {
        pw_get_element($elem, “el”.$i);
        $i++;
        }
        ?>

  • Drew

    I’m building a page that pulls in a group of posts based off a custom field. Now that I have this group of posts I want to use Relevanssi to search JUST from this group using terms set by the theme (not the user). Is this possible with the premium version? If not do you think it’s possible at all? Perhaps we can hire you to make the changes? Thanks!

    • If the group is based off a custom field, it should be fairly easy to do a relevanssi_hits_filter filter function that’ll restrict the search to only the posts you want.

      • Drew

        Great, thanks for the tip!

  • Max Hodges

    is there a Relevanssi wiki? I’d like to contribute an article.

    Here’s how to use relevanssi in plaec of keyword searches using wp_query:

    $wrx_search_txt = get_query_var('s');
     
     if (!empty($wre_search_txt))
        {	global $wp_query;
    		$rq = new WP_Query('s='.$wre_search_txt);
    		$rq->query_vars = $wp_query->query_vars;
    		relevanssi_do_query($rq);
         }

    then use $wp_query to get the posts i.e.

     have_posts()) : while ($wp_query->have_posts()) : $wp_query->the_post();
  • No wiki, but contributions to knowledge base and the user manual are certainly welcome.

  • web559

    I have a custom WP_Query in a post type search page which returns results with Relevanssi (Premium) off, but returns no results with Relevanssi on.

    Max Hodge’s code didn’t solve it for me, nor did wrapping $wp_query in relevanssi_do_query(). $wp_query->query_vars[‘s’] is already set, and is_search() evaluates to true. Relevanssi works fine on the main search page, just won’t work in this page template. There are no calls to query_posts() in the page or the widgets, though I do clone the query at the top ($temp_query = clone $wp_query;) if that matters.

    Any idea what might be going on? (I would even be fine completely disabling Relevanssi on this page.)

    • If $wp_query->query_vars[‘posts_per_page’] is not set, the search will not return results. That’s one thing you can check.

      Other than that it’s hard to say without seeing your page template.

  • web559

    I have removed everything else from the template, and the same thing happens—specifying any value for ‘s’ results in zero results.

    Here is the full template I am testing with: https://gist.github.com/3903803 and here is a dump of the WP_Query object: https://gist.github.com/3903820

    This is a post type archive page (—.com/posttype?s=test). The default search page works fine (—.com/?s=test). I’m perplexed.

    • As am I, I don’t know why this is happening. Very hard to say without taking a closer look – I’d debug this by checking what’s happening inside Relevanssi when it’s processing the query, adding var_dumps() here and there.

  • sk

    Hey web559 — did you ever solve this? I’m having the same issue.

    • web559

      Not yet, unfortunately, but I will post an update here if/when I do.

  • Umesh

    Hi Relevanssi team,

    Any update on this thread?

    Thanks!

  • Joe Jordan

    Hello! I’m adding “relevanssi_do_query($wp_query);” to my template, which makes the search page appear fine (nothing errors), but now my post page is missing the post content – it just goes from the top of the template to the bottom. Any clue as to why adding relevanssi_do_query($wp_query); would cause my post to error?

    • Do you have a relevanssi_do_query() call on your posts template? You probably shouldn’t. Have it on the search results template, not on the single post template. If those are the same for some reason, make sure relevanssi_do_query() only runs when you have a search (use is_search(), for example).

      • Joe Jordan

        I appreciate the help, but for some reason it’s still not working. On the search results page, I get “Search For”, and with debug on, I get the error: Notice: Trying to get property of non-object in C:inetpubwwwrootwordpresswp-includestemplate.php on line 553. However, I’m using Heroic Knowledgebase, which has it’s own search results page, here: http://pastebin.com/2eqUqrpQ.

        I’ve tried adding relevanssi_do_query about a million ways on both pages, but I can’t seem to get it to work. If I add it to the template.php page, it makes the posts appear blank. If I add it on the hkb-search.php page, it makes no change.

        Any help is appreciated, but I understand if you aren’t able to because this is such an unusual situation.

        Thank you!

        • Now the thousand dollar question: why are you using relevanssi_do_query() in the first place? What are you trying to achieve with it? 99% of the time it’s not necessary.

          • Joe Jordan

            🙂 I’m trying to enable “Create custom search result snippets” to get bolding in search results. However, when I enable that, the search results pages goes blank and shows only “Search For” (which is some part of word press’s screen reader). Adding relevanssi_do_query makes the search page reappear perfectly, but viewing a page (or knowledgebase “article” in my case) doesn’t show the title or content.

          • Sounds like you have shortcodes on your site that break the custom excerpts. relevanssi_do_query() should not fix that…

  • I’m trying to use Relevanssi to add a text search on top of some filtering (taxonomy- and date-based) on content listing pages. So the standard site-wide search isn’t triggered, I’m using a different query parameter for the text aspect (instead of ‘s’). I’m doing all the filtering by hooking into pre_get_posts and applying tax_query and meta_query to the query that’s getting the posts for listing. How to I apply the Relevanssi search here? Currently I’m doing a relevanssi_do_query( $query ) inside the pre_get_posts hook – but could that mess things up by populating the actual posts before WP_Query itself tried to query?

    • Use a separate query object that is not used for anything else, then the actual posts won’t be populated.

      • Thanks Mikko, but not sure I follow. The query is actually a custom query (I tend to not use the main query anyway). There’ll be a custom query run for each different listing page. Then I hook into pre_get_posts to apply potential search filters to any of these custom queries.

        • I’m not sure what the problem is, then. If you feed relevanssi_do_query() a query that is not used anywhere else, there can’t be any problems with the function populating some other query – it’ll only work on the exact query object you’re feeding it.

          • But if I run relevanssi_do_query( $query ) inside a function hooked to pre_get_posts, won’t the normal querying be done as well, on top of the Relevanssi query? Or will the fact that the query object is populated when it’s returned from pre_get_posts short-circuit the normal querying? Or doesn’t it matter?

          • This has no effect on any other querying going on. relevanssi_do_query() takes the query, populates it with posts and whatever else happens to it is not Relevanssi’s concern. If you’re using the same query object later, then yes, the Relevanssi results can be overwritten. pre_get_posts does happen before get_posts(), as it says.

            Which is why I assumed you’re actually using an unique query object that you’ll only use for relevanssi_do_query() and nothing else. Another option is to run Relevanssi later in the process.

          • OK, I guess the issue is marrying Relevanssi’s text search with the tax_query and meta_query stuff I’m also doing for filtering. Will relevanssi_do_query() respect all such parameters that are passed, as well as the text search parameter? So I’m bypassing WP_Query altogether?

          • Yes, Relevanssi understands almost all the same parameters as WP_Query, especially tax_query and meta_query.

          • OK thanks – just getting my head around the idea of bypassing WP_Query and avoiding pre_get_posts! One final thing – what’s the easiest way to generate a WP_Query object without the query being run, to then pass it to Relevanssi.

          • No idea really, $query = new WP_Query(); ?

          • Oh, maybe I’m misunderstanding – do I just pass the same query args to relevanssi_do_query() as I would to WP_Query()? You mentioned passing a WP_Query *object*, which seems like it would be tedious to create manually – but if you pass the args to WP_Query it’d do the query as well. Sorry if I’m getting this mixed up!

          • Yeah, it’ll do the query. There’s no way around that as far as I can tell.

          • Ah OK. Just my optimisation reflexes trying to avoid that! Thanks for the help.