Skip to content

Instantly share code, notes, and snippets.

@mariovalney mariovalney/functions.php
Last active Oct 4, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.