Reputation: 67
I have loop in functions.php with this code:
$meta_query[] = array(
'key' => '$key',
'value' => $value,
'compare' => 'IN',
);
and i trying to add next $meta_query after loop but with "<" in compare. When I add 'IN' it's working but when i change to '>=" or ">" it doesn't work.
$meta_query[] = array(
'key' => 'price',
'value' => $value,
'compare' => '>=',
);
Do you know why?
This is my fullcode:
// array of filters (field key => field name)
$GLOBALS['my_query_filters'] = array(
'field_1' => 'type',
'field_2' => 'price',
'field_3' => 'type2',
'field_4' => 'city',
'field_5' => 'price_min',
'field_6' => 'price_max',
);
function my_pre_get_posts( $query ) {
global $post;
global $wpdb;
$parametry = get_field_objects($post->ID);
if(!is_single() && $post->ID != 2 && $query->get( 'cat' )){
/* start filter*/
$meta_query = $query->get('meta_query');
foreach( $GLOBALS['my_query_filters'] as $key => $name ) {
// continue if not found in url
if( empty($_GET[ $name ]) ) {
continue;
}
// get the value for this filter
// eg: http://www.website.com/events?city=melbourne,sydney
$value = explode(',', $_GET[ $name ]);
// append meta query
if($name == 'price_min'){
$meta_query[] = array(
'key' => 'price',
'value' => $value,
'compare' => '>=',
);
}
elseif($name == 'price_max'){
$meta_query[] = array(
'key' => 'price',
'value' => $value,
'compare' => '<=',
);
}
else{
$meta_query[] = array(
'key' => $name,
'value' => $value,
'compare' => 'IN',
);
}
}
// update meta query
$query->set('meta_query', $meta_query);
In URL (and in table wp_postmeta) i have: type, type2, price and city. I don't have price_min and price_max so I want operate on price field.
This is my working array after filtering:
Array ( [0] => Array ( [key] => type [value] => Array ( [0] => flat) [compare] => IN ) [1] => Array ( [key] => city[value] => Array ( [0] => Cracow) [compare] => IN ) )
and this is not working array when I add price_min and price_max:
Array ( [0] => Array ( [key] => type [value] => Array ( [0] => flat) [compare] => IN ) [1] => Array ( [key] => city [value] => Array ( [0] => Cracow) [compare] => IN ) [2] => Array ( [key] => price [value] => Array ( [0] => 50000 ) [compare] => >= ) [3] => Array ( [key] => price [value] => Array ( [0] => 300000 ) [compare] => <= ) )
Upvotes: 0
Views: 1557
Reputation:
It's likely that the $value
is not an integer so trying to compare the value of it as an integer when it's a string will cause some issues. Before your WP_Query
arguments, place this code in your file:
$value = (int) $value;
Take a look at type juggling in PHP for more info.
This is the documentation for WP_Query
meta comparisons.
Upvotes: 1