Skip to content

Instantly share code, notes, and snippets.

@mariovalney
Last active October 4, 2017 01:34
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 mariovalney/e8646d8c64db36e9f239e6d05f2e5923 to your computer and use it in GitHub Desktop.
Save mariovalney/e8646d8c64db36e9f239e6d05f2e5923 to your computer and use it in GitHub Desktop.
Compare two meta_values in WP_Query
<?php
add_filter( 'posts_request', 'gist_posts_request' );
function gist_posts_request( $sql ) {
if ( strrpos( $sql, 'value_of_' ) === false ) {
return $sql;
}
$matches = array();
preg_match_all( "/'value_of_[^']*'/", $sql, $matches );
foreach ( $matches as $match ) {
$meta_key = substr( trim( $match[0], "'" ), 9 );
preg_match( "/mt[0-9]*.meta_key = '$meta_key'/", $sql, $meta_key_match);
if ( empty( $meta_key_match ) ) {
continue;
}
$meta_key = explode( '=', $meta_key_match[0] );
$meta_key = trim( $meta_key[0] );
$sql_to_add = "CAST($meta_key AS SIGNED)";
$sql = str_replace( $match[0], $sql_to_add, $sql );
}
return $sql;
}
/*
WP_Query 'meta_query' arg should be like this (with 'value_of_{meta_key}'):
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'meta_key_one',
'value' => 'value_of_' . 'meta_key_two',
'compare' => '>',
'type' => 'NUMERIC',
),
array(
'key' => 'meta_key_two',
'compare' => 'EXISTS',
)
),
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment