The WP_Query
has a feature called meta_query
. Using it allows you to either query by value or numeric value:
$car = new WP_Query( array(
'post_type' => array( 'cars' ),
'meta_key' => 'car_number',
'orderby' => 'meta_value_num',
'posts_per_page' => 1,
'order' => 'DESC',
'cache_results' => true,
) );
$carNr = get_post_meta( $car->ID, 'car_number', true );
// Inspect result
var_dump( $carNr );
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:
global $wpdb;
$wpdb->get_var(
"SELECT {$wpdb->postmeta}.meta_value
FROM {$wpdb->postmeta}
WHERE 1=1
AND {$wpdb->postmeta}.meta_key = 'car_number'
ORDER BY ABS( {$wpdb->postmeta}.meta_value ) DESC
LIMIT 0,1"
);
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
CAST( {$wpdb->postmeta}.meta_value as SIGNED INTEGER )
Note: If you don’t have negative integers, you can go with UNSIGNED
or
CONVERT( {$wpdb->postmeta}.meta_value, SIGNED INTEGER )