E.g. I have a meta field called car_number
:
So, normally I would try something like this to get this value:
$car_value = get_post_meta($post->ID, 'car_number');
But the porblem is that I need to get the row only where the car_number
is highest e.g. 45. so I need somehow to get the highest value and do something like this:
$post_ID = .. // here I need to get the ID of the post that has the biggest value in the fild car_value
$car_value = get_post_meta($post_ID, 'car_number');
how can I get the post_ID of the post that has the highest value (number) in car_value meta field?
The
WP_Query
has a feature calledmeta_query
. Using it allows you to either query by value or numeric value:Now, that we got the right post type, the appropriate meta key and defined that we want to order by its value, we only need to limit the result to a single post and have a descending order. As we now got the post, we can easily grab the meta value.
Another option would be to do a plain query:
Depending on how you saved your values – often plugins save numbers/digits/integers as strings – you may need to convert your value during the query. In that case replace the order by part with
Note: If you don’t have negative integers, you can go with
UNSIGNED
or
Try this method
from here. For me it worked fine.