Skip Navigation

[Résolu] Remove spaces from user input before using it as query filter

This support ticket is created Il y a 3 années et 2 mois. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

No supporters are available to work today on Toolset forum. Feel free to create tickets and we will handle it as soon as we are online. Thank you for your understanding.

Sun Mon Tue Wed Thu Fri Sat
- 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Karachi (GMT+05:00)

This topic contains 2 réponses, has 2 voix.

Last updated by zoeS Il y a 3 années et 2 mois.

Assisted by: Waqar.

Auteur
Publications
#1939455
Screenshot 2021-02-09 at 14.16.36.jpg
Screenshot 2021-02-09 at 14.14.54.jpg

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!

#1940413

Waqar
Supporter

Languages: Anglais (English )

Timezone: Asia/Karachi (GMT+05:00)

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

#1942233

My issue is resolved now. Thank you!

This ticket is now closed. If you're a WPML client and need related help, please open a new support ticket.