gpt4 book ai didi

wordpress - Woocommerce 产品的 WP_Query 中的 Orderby 价格

转载 作者:行者123 更新时间:2023-12-02 16:55:31 25 4
gpt4 key购买 nike

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

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

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

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

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

最佳答案

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

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.

参见 WooCommerce documentation

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

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

关于wordpress - Woocommerce 产品的 WP_Query 中的 Orderby 价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56549498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com