How to search for an exact match

GravityView's current search functionality doesn't use an exact match, it uses the contains operator, so if you search for the word "Kansas", results containing that word, like "Arkansas", will also show up:

Screenshot showing search results with 2 entries where the state is Arkansas and 1 entry with state as Kansas

If you wish to change the search functionality to look for an exact match, then you need the function below:

add_filter( 'gravityview_search_operator', function( $operator, $filter = array() ){


$run_on_views = [100,200]; //The IDs of the Views you'd like to affect [100,200,...]


if ( ! class_exists( '\GravityView_View_Data' ) ) {

return $operator;

}

$views = \GravityView_View_Data::getInstance()->views->all();

if(sizeof($views)){

foreach ( $views as $view ) {

if( in_array( $view->ID, $run_on_views ) ){

$operator = 'is';

}

}

}

return $operator;

}, 10, 2);


Here's the result:

Screenshot showing only one entry with Kansas as the State

Searching with empty values

If you have more than two fields on your Search Bar and leave one empty, the search will return the same results as before:

But if you want to require users to fill all fields for results to appear, then you'll also need to add this other code snippet below:

// This disallows empty field values

add_filter( 'gravityview/search/ignore-empty-values', function() {

return false;

});


This way, the search won't return any results until both fields are filled:

Screenshot showing a View with no results because one search field is empty

Screenshot showing a View with one result because the fields on the search bar are filled

This is perfect for restricting entry results to only those users that know particular details from their submission, like an SSN number in conjunction with a Zip Code or date of birth.


It's important to note that this won't prevent the search form from being submitted.


This will only cause GravityView to ignore the empty field, and the search results will be empty.


Defining strict matches for particular fields

If you need to target just a specific field from a specific form, then the code is a little bit more complex. To achieve that, we've created a simple plugin you can download here. You'll need to modify the Form ID and Field IDs inside that plugin's code using the plugin editor on your WordPress Dashboard:

 Please contact our supportif you need further assistance.

Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.

Still need help? Contact Us Contact Us