简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM