Skip to content

Instantly share code, notes, and snippets.

@jag1989
Created June 22, 2017 13:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jag1989/e017945b9ad8ea6f79e9e7419d27cce7 to your computer and use it in GitHub Desktop.
Save jag1989/e017945b9ad8ea6f79e9e7419d27cce7 to your computer and use it in GitHub Desktop.
WordPress REGEXP for meta_query key
function meta_query_key_compare( $query ) {
$meta_query = $query->get('meta_query');
if(empty($meta_query)) {
return;
}
$marker = '__tmp_marker__';
$rx = [];
foreach($meta_query as $key => $meta_query_part) {
if(isset($meta_query_part['key_compare']) && in_array( strtoupper($meta_query_part['key_compare']), ['REGEXP', 'RLIKE', 'LIKE']) && isset($meta_query_part['key'])) {
$meta_query_part['key'] .= $marker . $key; //so we can find it later
$query->query_vars['meta_query'][$key]['key'] = $meta_query_part['key'];
$rx[$key] = $meta_query_part;
}
}
foreach($meta_query as $key => $meta_query_part) {
foreach ($meta_query_part as $key_i => $meta_i) {
if (count($meta_i) >= 3) {
if (isset($meta_i['key_compare']) && in_array( strtoupper($meta_i['key_compare']), [ 'REGEXP', 'RLIKE', 'LIKE']) && isset($meta_i['key'])) {
$meta_i['key'] .= $marker . $key_i;
$query->query_vars['meta_query'][$key][$key_i]['key'] = $meta_i['key'];
$rx[$key][$key_i] = $meta_i;
}
}
}
}
if(empty($rx)) {
return;
}
add_filter('get_meta_sql', function($sql) use ($rx, $marker) {
static $nr = 0;
if(0 != $nr++) {
return $sql;
}
foreach($rx as $key => $meta_query_part) { //replace the markers
if( isset($meta_query_part['key'])) :
$sql['where'] = str_replace(
sprintf(
".meta_key = '%s' ",
$meta_query_part['key']
),
sprintf(
".meta_key %s '%s' ",
$meta_query_part['key_compare'],
str_replace(
$marker.$key,
'',
$meta_query_part['key']
)
), $sql['where']
);
endif;
}
foreach ($rx as $key => $meta_query_part) {
if (!isset($meta_query_part['key'])) {
foreach ($meta_query_part as $key_i => $part_i) {
$sql['where'] = str_replace(
sprintf(
".meta_key = '%s' ", $part_i['key']
), sprintf(
".meta_key %s '%s' ", $part_i['key_compare'], str_replace(
$marker . $key_i, '', $part_i['key']
)
), $sql['where']
);
}
}
}
return $sql;
});
}
add_action('pre_get_posts', 'meta_query_key_compare', 999);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment