user11283889
user11283889

Reputation:

Orderby price in a WP_Query for Woocommerce products

I have this code that i need to get all product order by price :

I'm trying to sort my products by price but it doesn't work fine.

This is my code to get products, it works fine if I don't use the "orderby".

$args = array(
    'post_type'=> 'product',
    'meta_key' => 'price',
    'orderby' => 'meta_value_num',
    'order' => 'ASC'
);
$wooCommerceargs = new WP_Query( $args );

But the problem is no any product show !

Upvotes: 3

Views: 6048

Answers (2)

nh-labs
nh-labs

Reputation: 679

that works perfectly in 2022

$args = array(
'post_type'=> 'product',
'orderby' => '_price',   //price metakey is '_price' !
'order' => 'ASC'
);
$wooCommerceargs = new WP_Query( $args );

Upvotes: 0

Christian Lescuyer
Christian Lescuyer

Reputation: 19263

First, do not use WP_Query() or get_posts(). From the WooCommerce doc:

wc_get_products and WC_Product_Query provide a standard way of retrieving products that is safe to use and will not break due to database changes in future WooCommerce versions. Building custom WP_Queries or database queries is likely to break your code in future versions of WooCommerce as data moves towards custom tables for better performance.

See WooCommerce documentation

Second, you cannot order by price directly in the query. Get your products then call the wc_products_array_orderby() function.

$args     = array(); // Optional arguments
$products = wc_get_products( $args );
$ordered  = wc_products_array_orderby( $products, 'price', 'ASC' );

Upvotes: 9

Related Questions