获取按“菜单顺序”排序的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>';
}

两种方法都可以。