【问题标题】:Orderby price in a WP_Query for Woocommerce productsWoocommerce 产品的 WP_Query 中的 Orderby 价格
【发布时间】:2019-06-11 18:10:42
【问题描述】:

我有这个代码,我需要按价格获取所有产品订单:

我正在尝试按价格对我的产品进行分类,但效果不佳。

这是我获取产品的代码,如果我不使用“orderby”,它可以正常工作。

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

但问题是没有任何产品展示!

【问题讨论】:

标签: wordpress woocommerce


【解决方案1】:

首先,不要使用WP_Query()get_posts()。来自 WooCommerce 文档:

wc_get_products 和 WC_Product_Query 提供了一种检索产品的标准方法,该方法可以安全使用并且不会因未来 WooCommerce 版本中的数据库更改而中断。随着数据向自定义表移动以获得更好的性能,构建自定义 WP_Queries 或数据库查询可能会破坏您在未来版本的 WooCommerce 中的代码。

WooCommerce documentation

其次,您不能直接在查询中按价格订购。获取您的产品,然后调用wc_products_array_orderby() 函数。

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

【讨论】:

    【解决方案2】:

    在 2022 年完美运行

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

    【讨论】:

      猜你喜欢
      • 2018-08-30
      • 1970-01-01
      • 1970-01-01
      • 2018-08-26
      • 1970-01-01
      • 1970-01-01
      • 2017-11-25
      • 2021-05-19
      • 2017-03-10
      相关资源
      最近更新 更多