Skip to content

Instantly share code, notes, and snippets.

@ethanclevenger91
Last active January 17, 2018 14:37
Show Gist options
  • Save ethanclevenger91/447e517a4fc4d0b79247 to your computer and use it in GitHub Desktop.
Save ethanclevenger91/447e517a4fc4d0b79247 to your computer and use it in GitHub Desktop.
Use a comparison operator for your WordPress `meta_query` key - inspired by http://wordpress.stackexchange.com/questions/193791/use-regexp-in-wp-query-meta-query-key
add_action('pre_get_posts', 'meta_query_key_compare');
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;
}
}
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
$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']
);
}
return $sql;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment