I have a search by reference form that takes a user input and looks to match it against a custom field. It works perfectly if the user input exactly matches the custom field (e.g. AB12345), but not if it contains spaces (e.g. AB 12345). Is there any way I can sanitise the user input to remove spaces before using it as the filter? Attached are screenshots of my form and of the query filter. Many thanks!
Hi,
Thank you for contacting us and I'd be happy to assist.
You can use the "wpv_filter_query" filter to strip spaces from the value entered by the user in a specific custom search field:
https://toolset.com/documentation/programmer-reference/views-filters/#wpv_filter_query
For example, suppose you have a view with ID "1234" and the custom field with slug "reference". The code to filter spaces would look like this:
add_filter( 'wpv_filter_query', 'wpv_filter_query_func', 1000 , 3 );
function wpv_filter_query_func( $query_args, $view_settings ) {
// skip if blocks edit screen
if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
return $query_args;
}
// process if specific view
if ( !is_admin() && ( isset($view_settings['view_id']) && $view_settings['view_id'] == 1234) ) {
if( !empty($query_args['meta_query']) ) {
for ($i=0; $i < (count($query_args['meta_query'])-1) ; $i++) {
if ( $query_args['meta_query'][$i]['key'] == 'wpcf-reference' ) {
$query_args['meta_query'][$i]['value'] = str_replace(' ', '', $query_args['meta_query'][$i]['value']);
}
}
}
}
return $query_args;
}
I hope this helps.
regards,
Waqar
My issue is resolved now. Thank you!