如何解决获取按“菜单顺序”排序的WooCommerce特定产品属性术语
我想按照当前产品的menu_order对get_the_terms进行排序,直到现在我有了以下代码:
$colors='';
$terms = get_the_terms( get_the_ID(),'pa_colors' );
foreach ( $terms as $term ) {
$colors='<pre>'.$term->name.'</pre>';
}
echo $colors;
解决方法
有两种方法来获取按菜单顺序(对于已定义产品) 进行排序的产品属性术语名称:
1)。使用wp_get_post_terms()
函数 (WordPress方式)
WordPress功能get_the_terms()
不允许更改WP_Term_Query
…
因此,您将使用类似的wp_get_post_terms()
来进行WP_Term_Query
调整。
$taxonomy = 'pa_color'; // The taxonomy
$query_args = array(
'fields' => 'names','orderby' => 'meta_value_num','meta_query' => array( array(
'key' => 'order_' . $taxonomy,'type' => 'NUMERIC'
) )
);
$term_names = wp_get_post_terms( get_the_ID(),$taxonomy,$query_args );
if ( ! empty( $term_names ) ) {
// Output
echo '<pre>' . implode( '</pre><pre>',$term_names ) . '</pre>';
}
2)。只需使用WC_Product
方法get_attribute()
(WooCommerce方式)
$product = wc_get_product( get_the_ID() ); // The WC_product Object
$taxonomy = 'pa_color'; // The taxonomy
$names_string = $product->get_attribute('color');
if ( ! empty( $names_string ) ) {
$names_array = explode( ',',$names_string ); // Converting the string to an array of term names
// Output
echo '<pre>' . implode( '</pre><pre>',$names_array ) . '</pre>';
}
两种方法都可以。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。