使用 WooCommerce wc_get_product_terms 函数对产品属性术语进行排序

Joe*_*van 3 php sorting wordpress woocommerce taxonomy-terms

我有一个由 WooCommerce 提供支持的电子商务网站。我使用产品变体来允许我的客户为其产品选择特定配置。

我使用以下代码列出特定产品属性的术语名称:

$available_pa_colors = wc_get_product_terms( $product->get_id(), 'pa_colors' );    
Run Code Online (Sandbox Code Playgroud)

而且效果很好。

但是,当将默认排序顺序从“自定义排序”更改为“术语 ID”时,我什么也没得到(没有显示术语名称)。

我做了一些研究,似乎 wc_get_product_terms 不适用于排序。
如何让这些术语按术语 ID 排序?

任何有关此的曲目都将受到赞赏。

Loi*_*tec 5

该功能wc_get_product_terms()使用优先存储的缓存数据而不是其中包含的WordPress 的使用。 这就是为什么你无法排序任何东西。_wc_get_cached_product_terms() wp_get_post_terms()

因此,您应该直接使用wp_get_post_terms()它允许排序,如下所示:

$available_pa_colors = wp_get_post_terms( $product->get_id(), 'pa_colors', array(
    'orderby' => 'term_id', 'order' => 'ASC', 'fields' => 'names'
) );
Run Code Online (Sandbox Code Playgroud)

经过测试并有效。