How to get the db table row that has the biggest value in the meta value?

E.g. I have a meta field called car_number:

So, normally I would try something like this to get this value:

Read More
$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?

Related posts

2 comments

  1. 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 )
    
  2. Try this method

    function end_meta_value( $end = "max", $meta )
    {
        global $wpdb;
        $query = $wpdb->prepare( 
            "SELECT %s( cast( meta_value as UNSIGNED ) ) FROM {$wpdb->postmeta} WHERE meta_key='%s'",
            $end,
            $meta
        );
        return $wpdb->get_var( $query );
    }
    

    from here. For me it worked fine.

Comments are closed.