When you add a text field filter to a View the comparisons include ‘=’ where the whole string should match, or ‘LIKE’ where any part of the string should match, but it’s not possible to use a comparison such as “BEGINS WITH” where the start of the field should match the search term.
Regular expressions can be included in post meta queries, but you will need to use the Views API to modify the query arguments.
In the following code for the specified fields the query will be updated so that the start of the field value must match the search term, allowing searches such as “all posts where the custom field begins with B”:
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);
Let us know if this snippet is not working for you:
This snippet doesn’t work