'Get the product with highest price in Woocommerce

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?



Solution 1:[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 );

Solution 2:[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'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 honk31
Solution 2 Ankit Prajapati