Manual search results filtering

If the filtering capabilities that Relevanssi provides are not enough, you can take the manual approach and filter the results by whatever you want.

To do that, you need to use the relevanssi_hits_filter filter hook. Here’s how you filter by custom field. Let’s assume you have a custom field called “colour” and want to use a query variable colour to filter results like this: http://www.example.com/?s=ford&colour=red.

First you have to introduce your query variable to WordPress, otherwise WP will just clean it out. Add all the code to your theme’s functions.php.

add_filter('query_vars', 'relevanssi_qvs');
function relevanssi_qvs($qv) {
    $qv[] = 'colour';
    return $qv;
}

Now the query variable will be passed through. Then, the filter:

add_filter('relevanssi_hits_filter', 'relevanssi_colour_filter');
function relevanssi_colour_filter($hits) {
    global $wp_query;
    if (isset($wp_query->query_vars['colour'])) {
    	$correct_colour = array();
    	foreach ($hits[0] as $hit) {
    		$colour = get_post_meta($hit->ID, 'colour', true);
    		if ($colour == $wp_query->query_vars['colour']) $correct_colour[] = $hit;
    	}
    	$hits[0] = $correct_colour;
    }
    return $hits;
}

Let’s assume we’re interested in user profiles. The user meta field is still the same colour, but this time we only want users. The function doesn’t change much:

function relevanssi_colour_filter($hits) {
    global $wp_query;
    if (isset($wp_query->query_vars['colour'])) {
    	$correct_colour = array();
    	foreach ($hits[0] as $hit) {
    		if ($hit->post_type == 'user') {
	    		$colour = get_user_meta($hit->ID, 'colour', true);
    			if ($colour == $wp_query->query_vars['colour']) $correct_colour[] = $hit;
    		}
    	}
    	$hits[0] = $correct_colour;
    }
    return $hits;
}

34 comments Manual search results filtering

  1. Would you be able to add this to the search form via a text input field? EG my client has publications set up as posts and wants to be able to search by publication date. I have added a custom field called pub_date and was hoping to use this plugin to allow the users to input what date (ie year) they want to search (along with the category/taxonomy).

    Any help would be greatly appreciated!
    Thanks
    Jen

    P.S. I’m using the premium plugin.

  2. Yes, the code doesn’t care about the input field – in the example “colour” can be text input field, dropdown, checkbox or whatever you wish. The value is only thing that matters for this code.

    The code should pretty much work as it is, if you just change every “colour” to “pub_date”.

  3. WOW that was the fastest response time ever! Thanks very much ๐Ÿ™‚

    okay so if I add the above code into my functions.php file, replace every colour with pub_date, then I should be able to add a text input field to the search form that will filter the results by publication date?

    Currently my search form is this:
    <form method="get" class="searchform" action="” >

    Limit search to:

    ‘All categories’,
    ‘orderby’ => ‘name’
    ) ); ?>

    Research Topic:

    Fact Sheet:

    It includes two custom taxonomies already. I’m just a bit lost as to how to add code to the form to include the custom field input area. If you had any ideas that would be great!

    Thanks again for the quick response.

  4. After browsing Relevanssi code, I found the “Custom fields to index” setting in the administration settings page. I had not seen this previously, and appears that it will accomplish what I need.

  5. “colour” is the custom field name? in that case, a checkbox to select the colour would be like this? RED

      1. Ok, a little help if you can:

        Just to explain:
        My custom field name is “categoria_profissional”. It is a checkbox field. I want to display several checkboxes with the values of this field on a search page. The user will select one of the “categoria_profissional” value and will click on search or will add some text on the search field.

        Ok, now, im trying your code like this:

        add_filter(‘query_vars’, ‘relevanssi_qvs’);

        function relevanssi_qvs($qv) {

        $qv[] = ‘categoria_profissional’;

        return $qv;

        }

        function relevanssi_colour_filter($hits) {

        global $wp_query;

        if (isset($wp_query->query_vars[‘categoria_profissional’])) {

        $correct_categoria = array();

        foreach ($hits[0] as $hit) {

        if ($hit->post_type == ‘user’) {

        $categoria = get_user_meta($hit->ID, ‘categoria_profissional’, true);

        if ($categoria == $wp_query->query_vars[‘categoria_profissional’]) $correct_categoria[] = $hit;

        }

        }

        $hits[0] = $correct_categoria;

        }

        return $hits;

        }

        And my search is like this:

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

        But it didnt work, maybe if you could just read to see if i did something wrong with the code, it would be great!

        1. How it didn’t work? Have you debugged the code at all, to see where it goes wrong? Is the $wp_query->query_vars[‘categoria_profissional’] set? If it is, what’s in it? Does the get_user_meta() fetch the correct data?

          Go through the functions and see where it doesn’t work like it should.

          (If you have a Premium license, please use the Premium support.)

  6. Hi Mikko, i’m trying to make your plugin work with xili language plugin. but it seems that i’m missing something. i used this function and add the lang as custom parameter but it didn’t work. can you please help

    1. I don’t know how the Xili language plugin works, but take a look at lib/common.php for the WPML and Polylang compatibility function – that’s probably what you need to do with Xili.

      1. Thanks Mikko for your response, basicaly we can add a paramater to wp query which is lang to query elements by language. I don’t know if there is any possibility to do the same with your powerfull plugin.
        I’ve added a parameter to the search from but i don’t think that it is taken in consideration.

        1. Relevanssi can be made compatible with Xili, but as I don’t know how Xili works, I don’t know exactly how. Relevanssi needs to be told how to interpret that “lang” parameter, or you can use it to filter the results afterwards, like is done with WPML and Polylang.

      2. Thanks a lot mikko, here is how i’ve made it work with xili-language perhaps you will have better idea than me:

        add_filter(‘query_vars’, ‘relevanssi_qvs’);

        function relevanssi_qvs($qv) {

        $qv[] = ‘lang’;

        return $qv;

        }

        add_filter(‘relevanssi_hits_filter’, ‘search_post_by_lang’);

        function search_post_by_lang($hits) {

        $post_by_lang = array();

        $current_lang = get_query_var( ‘lang’,’fr_fr’);

        $filtred_post = array();

        foreach ($hits[0] as $hit) {

        $id = xl_get_linked_post_in ($hit->ID, $current_lang, ‘id’);

        if(isset($id) && is_string ($id) && !in_array($id,$filtred_post)){

        $filtred_post[] = $id;

        $post_by_lang[] = $hit;

        }

        }

        $hits[0] = $post_by_lang;

        return $hits;

        }

        i hope it can help someone. i’m not sure if it is well coded.
        thanks

  7. hi, I use your plugin but when I search for example -> now you see me, there’s no result. is there any filter on the plugin? how I can disable it. thanks

  8. Hi Mikko, I’ve used your plugin many times already, but I have another question for a new project.

    Is it possible to index using post title and content, but then choose which to use when searching on the front end? For example, can I enter a search term, and then select a radio button of ‘Search by title only’ or ‘Search all content’?

    1. Yes, but it’s somewhat complicated. You can use the relevanssi_match filter to recalculate the weights, and there you will know whether the hit was found in titles or in content, and you can use that to zero the weight if the hit was in the wrong place.

      1. Hi Mikko and Keith, have you got further with this issue, or a code example of how that could be done? I need a simple search box that searches for strings in my custom post titles, and that seems to be quite a problem, any help appreciated.

  9. Hi Mikko. I use Relevanssi with Woocommerce. I want to realize a seach by sku (the sku is the article number of the product (_sku field). The sku is an ISBN such like 978-3-8474-1235-8. I want, that the product with exact this sku is shown at first. At the moment, it would be shown at the end of the list. I want also that the product can be found, when the user types in this sku in the search query without the “-” or with blanks instead of the “-“. Do you have an idea, how to realize this? Kind regards, Maik

  10. Hello Mikko, great plugin!I just found it and started exploring. Can I use same logic as category filter to make the filter by Post Type? Thank you

Leave a Reply

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