Problem:
How to add a custom search for some field where the field value starts with the search term (rather than the normal behaviour where the search term can appear anywhere inside the field value).
Solution:
It is not supported within the UI, but you can use the Views API to customise the query arguments to take advantage of the ability to use regular expressions in meta queries.
Following is an example of such code, which needs editing for the ID(s) of the View(s) it should apply to, and the custom fields which should use this approach:
function tssupp_filter_query($view_args, $view_settings, $view_id) { $views = array( 167 ); // comma-separated array of View IDs to modify $fields = array( 'wpcf-searchable' ); // comma-separated array of fields to modify filter of, including wpcf- prefix if ( in_array($view_id, $views ) && isset( $view_args['meta_query'] ) ) { $meta_queries = $view_args['meta_query']; foreach ($meta_queries as $key => $meta_query) { if ( in_array( $meta_query['key'], $fields ) ){ $view_args['meta_query'][$key]['value'] = '^'.$meta_query['value']; $view_args['meta_query'][$key]['compare'] = 'REGEXP'; } } } return $view_args; } add_filter('wpv_filter_query', 'tssupp_filter_query', 101, 3);
Relevant Documentation:
https://toolset.com/documentation/programmer-reference/views-filters/#wpv_filter_query
https://developer.wordpress.org/reference/classes/wp_query/#custom-field-post-meta-parameters
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.
Sun | Mon | Tue | Wed | Thu | Fri | Sat |
---|---|---|---|---|---|---|
- | 7:00 – 14:00 | 7:00 – 14:00 | 7:00 – 14:00 | 7:00 – 14:00 | 7:00 – 14:00 | - |
- | 15:00 – 16:00 | 15:00 – 16:00 | 15:00 – 16:00 | 15:00 – 16:00 | 15:00 – 16:00 | - |
Supporter timezone: Europe/London (GMT+00:00)
This topic contains 2 replies, has 2 voices.
Last updated by 5 years, 6 months ago.
Assisted by: Nigel.