skip to Main Content

I need to retrieve the product with highest price in whole database.

I’ve tried this but doesn’t work.

$args = [
     'limit'     => '1',
     'orderby'   => 'price',
     'order'     => 'DESC',
];

$_query = new WC_Product_Query( $args );
$_products = $_query->get_products();

it gaves me a Query with 18 items, so neither ‘limit’ works like expected.

Any suggestion?

2

Answers


  1. A single query is probably the easiest.

    global $wpdb;
    $sql = "SELECT MAX(meta_value), post_id from {$wpdb->prefix}postmeta where meta_key = '_price'";
    
    $result = $wpdb->get_results($sql);
    
    $_product = wc_get_product( $result[0]->post_id );
    
    Login or Signup to reply.
  2. I came to the same issue, and tried the above query as it had the green tick, but after trying found that the query on the meta_value field compares the string and it is not considering the integer values.

    So for example if you have following pricing 15, 250, 16800, it will show the max value as 250, instead max value is 16800. so for that you will have to CAST to integer.

    Below query works perfect and is tested in current version of woocommerce

    SELECT MAX( CAST(meta_value AS UNSIGNED )) max_v FROM wp_postmeta where meta_key = '_price'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search