C. Wood C. Wood - 3 months ago 13
PHP Question

Ordering products by price in custom wp_query loop

I currently have a very simple wp_query loop to loop through my WooCommerce products like so:

$args = array(
'posts_per_page' => -1,
'product_cat' => $cat,
'post_type' => 'product',
'orderby' => 'price',
'order' => 'DESC'
);

$the_query = new WP_Query( $args );

while ( $the_query->have_posts() ) {
$the_query->the_post();
wc_get_template_part( 'content', 'product' );
}


This works as I want it to, except I can't get it to order the products by product price (ascending or descending) - what do I need to do to make this work?

Answer

Try this:

$args = array(
    'posts_per_page' => -1,
    'product_cat' => $cat,
    'post_type' => 'product',
    'orderby' => 'meta_value_num',
    'meta_key' => '_price',
    'order' => 'asc'
);

Hope it will help you.

Comments