Posted on

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.

Here’s a basic example of building a query object and then passing it to the relevanssi_do_query():

$args  = array(
    's'           => 'search terms',
    'numberposts' => 10,
    // Add the required parameters here.
);

$query = new WP_Query();
$query->parse_query( $args );

relevanssi_do_query( $query );
foreach ( $query->posts as $post ) {
    // Loop through the posts and do whatever you want with them.
}

You want to use parse_query() instead of the standard method of passing the arguments array to the WP_Query constructor, because the constructor runs the query immediately, but parse_query() doesn’t, so you avoid running an unnecessary query.

61 comments Direct access to the query engine

  1. 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!

  2. 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)`?

      1. 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.

        1. 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.

          1. 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.

        2. 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.

  3. 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?

  4. 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 ?

  5. 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.

      1. 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++;
        }
        ?>

  6. 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!

    1. 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.

  7. 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();
  8. 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.)

    1. 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.

    1. 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.

  9. 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?

    1. 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).

      1. 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!

        1. 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.

          1. 🙂 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.

  10. Hello
    Thanks for the great plugin!
    I am trying to use relevanssi_do_query() but get the error

    Fatal error: Call to undefined function relevanssi_do_query() in /home/secretbu/tugeza.net/theukrainians/wp-content/themes/theukrainians/search.php on line 10

    What may I do wrong?

    Thanks in advance

  11. 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?

      1. 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.

        1. 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.

          1. 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?

          2. 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.

          3. 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?

          4. 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.

          5. 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!

      1. Thanks Mikko.

        I have three Ajax queries that run side by side, each querying a different post type:
        – users
        – articles
        – projects

        If I tick the Relevannsi setting for “Index and search user profiles” I get user profiles appearing in all queries regardless of the ‘post_type’ being queried. Is there’ a way to stop this?

        Here’s a sample of my code:


        $args = array(
        ‘post_type’ => ‘project’,
        ‘posts_per_page’ => 3,
        ‘s’ => $_POST[‘searchTerm’]
        );
        $wp_query = new WP_Query( $args );
        relevanssi_do_query($wp_query);
        if($wp_query->have_posts()):
        // and so on…

        Thanks,
        Matt

        1. If you set a post type, users should not be included, unless you also specify user. Which version of Premium are you using? This is something that hasn’t worked properly in older versions, if your version is older than 1.15.3, then yeah, that’s why. In that case upgrading to current version will help.

      2. Also if I set the post_type to ‘user’ it doesn’t appear to work…

        $args = array(
        ‘post_type’ => ‘user’,
        ‘posts_per_page’ => 3,
        ‘s’ => $_POST[‘searchTerm’]
        );
        $wp_query = new WP_Query( $args );
        relevanssi_do_query($wp_query);
        if($wp_query->have_posts()):
        // and so on…

  12. Hi Mikko,

    I have a custom search page for a single CPT with complex wp_query that contains: string , meta and tax search all together.

    Unfortunately WP does not allow string AND meta/tax search in a single query (donno why) so currently I run 2 queries and than I’m combining them.

    Now the client can up with this request to sort results based on relevance, so I’m trying to implement Relevanssi on that query.

    With the current state where there are 2 queries – is it possible to pass both to Relevanssi and get one stream on results ordered b relevance?
    Or better – can Relevanssi itself run such search (string, meta & tax) all together?

    Agreed with the client that it it works be buy Premium… 🙂

    Many thanks!
    Eli

    1. Eli, WordPress definitely allows search term combined with meta and tax queries. Relevanssi can also do that. Just put the search term, tax_query and meta_query in the same query and pass it to Relevanssi, no problems.

  13. Hi guys, awesome plugin! Quick question: When I’m using the default wordpress search (via the “s” url param), the results have part of the content with the highlighted terms. How can we get the same result by using the relevanssi_do_query() function?

    Thank you in advance. Kind regards,
    Stratos

    1. When you use relevanssi_do_query(), Relevanssi generates the highlighted excerpts and stores them in the posts. The excerpt with the highlighted terms is in $post->post_excerpt.

  14. I’m using Elementor’s Archive Search Results Archive template. When I activate Relevanssi plugin, no posts show up on the Search Results page.

    Elementor’s template’s Posts widget does allow you to do some server-side custom query filtering, like this (https://developers.elementor.com/custom-query-filter/):

    [code]
    // Filter query on Search Results page with Ajax Search Lite plugin results
    add_action( ‘elementor/query/asl_custom_search_query’, function( $query ) {

    $query->set( ‘meta_query’, $meta_query );
    } );
    [/code]

    I’m assuming somehow I need to pass Relevanssi’s query into Elementor’s filter hook before it posts on the search results page? Not sure… any help would be appreciate on how I can achieve this.

    Thank you.

    1. I don’t think that filter is going to help. You could run Relevanssi on it with relevanssi_do_query( $query );, but it Elementor then runs the query again, the Relevanssi results will be wiped out. In order to make this template work with Relevanssi, changes would be needed under the hood. What exactly, I don’t know, as I don’t have any access to the Elementor source code.

Leave a Reply to Mikko Saari Cancel reply

Are you a Relevanssi Premium customer looking for support? Please use the Premium support form.

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