在自定义 wp_query 循环中按价格订购产品

C. *_*ood 2 php wordpress woocommerce

我目前有一个非常简单的 wp_query 循环来循环我的 WooCommerce 产品,如下所示:

$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' );
}
Run Code Online (Sandbox Code Playgroud)

这可以按我的意愿工作,但我无法按产品价格(升序或降序)订购产品 - 我需要做什么才能使其正常工作?

Nom*_*man 6

尝试这个:

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

希望它会帮助你。

  • 好吧,这是您应该阅读 https://codex.wordpress.org/Class_Reference/WP_Meta_Query 的链接。如果它解决了您的目的,请投票并接受答案。谢谢! (2认同)
  • 这对我不起作用,我看到一个价格为 1.50 的产品,然后是一个价格为 1.30 的产品... (2认同)