Posted on

Adding a custom field filter in the search

Adding a custom field filter in a Relevanssi search takes a little bit of programming, because the filter needs to create a meta_query that Relevanssi understands.

Let’s assume we have some colour information in a custom field that’s called colour_field, and we want to use that to filter the search results. First, let’s add a dropdown in our search form:

<select name="colour">
    <option value="any">Any colour</option>
    <option value="red">Red</option>
    <option value="green">Green</option>
</select>

Then, we need to tell WordPress that we want to use a query variable called colour (the name here needs to match the name attribute of the select in the form):

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

Then we need a function that reads in the query variable, formulates a meta_query and passes that to Relevanssi:

add_filter('relevanssi_modify_wp_query', 'rlv_add_meta_query');
function rlv_add_meta_query($query) {
	if (isset($query->query_vars['colour'])) {
		if (!empty($query->query_vars['colour'])) {
			$meta_query = array(
				array(
					'key' 		=> 'colour_field',
					'value'		=> $query->query_vars['colour'],
					'compare' 	=> '=',
				),
			);
			$query->set('meta_query', $meta_query);
		}
	}
	return $query;
}

If you need to have multiple meta fields in the same search, you must add them to the same meta_query – you can only have one. WP_Query documentation has a good example of what that looks like, so take a look at that if you need multiple custom fields.

  • Maurilio Santana

    The changes is on Relevanssi or on other plugin? For example, on my plugin.

    • These sample codes go to your theme. No need to edit any plugins.

  • isidrocalabuig

    Is necessary buy the premium version to do that? I try to use that code with no success with the free version. Thank you.

    • No, this will work with the free version as well.

      • isidrocalabuig

        Sorry, i think the example explains how to search by a dropdown box without using the input field. A missunderstanding.

  • JesWhite

    hi. i have i metadata named chkbox2 and there is a value again. i want to add this values to searching… but i cant add. how can i add ?

    • Relevanssi settings, “Custom fields to index”, add “chkbox2” to the list and rebuild the index.

      • JesWhite

        i’m trying now. i looked my database. this plugin creating cache. very nice. but i want to ask a question again. is it recreate again cache after new posts…?

        • If you mean the index then yes, Relevanssi indexes automatically when you add new posts.

          • JesWhite

            very nice. i liked that. i’m trying but i cant activate custom post meta field. post_meta chkbox2 not indexing and again i want to fix it. because your addon is perfect.

          • Have you set Relevanssi to index custom fields? Have you rebuilt the index afterwards?

          • JesWhite

            http://prntscr.com/edn7ji my setting is here. is there any problem. i rebuild it.

            i saw now i set up false..
            i will try again. and back…

          • That’s the “Extra user field” option, for user fields. User fields are for user profiles, not for post meta. The “Custom fields to index” option is empty, you should have the custom field name there.

          • JesWhite

            rebuilding now. slow because db is big.and worked fine now. i’m realy idiot ๐Ÿ™‚ because i’m trying for 3 hours ๐Ÿ™‚

            thanks a lots.

      • JesWhite

        i recreate and not worked. ๐Ÿ™ this chkbox2 is post_meta. is this problem ?

  • andreitp1

    Is there a way to filter custom field results based on _GET parameters? Here’s what I’m trying to achieve:
    mysite.com/?s=keyword&mycustomfield=customvalue

    This should return posts that match the search keyword AND that have the custom field “mycustomfield” set to the value “customvalue”.

    • Sure, just use the example above, but instead of looking at $query->query_vars, fetch the parameters from the $_GET array.

  • Luigi Briganti

    Hi,
    I followed this steps but still the search results doesn’t match anything. Plus, the search template used is actually the “content.php” one. How can I tell the system to show results with a particular template?

    • See WordPress template hierarchy. WordPress will use search.php, if it exists.

      Is the search using Relevanssi? Is the relevanssi_modify_wp_query filter being triggered? (If you add a var_dump($query); exit(); in the function before return $query;, what do you see?

      • Luigi Briganti

        where should I place those functions?