I have a custom field named ‘rating’ that holds decimals from 1.0 to 10. I am trying use wp_query to get me all the posts with a rating of 8.0 to 10. What I have so far almost works perfectly but it does not return posts with rating of 10.
<?php add_filter('get_meta_sql','cast_decimal_precision');
function cast_decimal_precision( $array ) {
$array['where'] = str_replace('DECIMAL','DECIMAL(1,1)',$array['where']);
return $array;}
?>
<?php
$args = array(
'posts_per_page' => 10,
'paged' => get_query_var( 'paged' ),
'category_name' => ( 'movies' ),
'meta_query' => array(
array(
'key' => 'rating',
'value' => 8,
'compare' => '>'
)
),
'meta_key' => 'rating',
'orderby' => 'meta_value',
'order' => 'DESC'
);
$wp_query = null;
$wp_query = new WP_Query($args);
?>
1 Answer
The issue is that the default comparison for meta_query
is a CHAR
comparison, so the order that the numbers would be in by default would be 1, 10, 2, 3, 4, 5, 6, 7, 8, 9, a, etc. To resolve this you need to modify your meta_query
as follows:
'meta_query' => array(
array(
'key' => 'rating',
'value' => 8,
'compare' => '>=',
'type' => 'NUMERIC'
)
),