Search code examples
phpwordpresswoocommerceproducttaxonomy-terms

Get WooCommerce specific product attribute terms sorted by "menu order"


I want to sort get_the_terms by menu_order of the curent product and till now i have this code:

$colors='';

$terms = get_the_terms( get_the_ID(), 'pa_colors' );
            
foreach ( $terms as $term ) {
        $colors='<pre>'.$term->name.'</pre>';
}
echo $colors;


Solution

  • There is 2 ways to get the product attribute term names sorted by menu order (for a defined product):

    1). Using wp_get_post_terms() function (WordPress way)

    The WordPress function get_the_terms() doesn't allow to alter the WP_Term_Query

    So instead you will use similar wp_get_post_terms() that allows WP_Term_Query tuning.

    $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). Simply using WC_Product method get_attribute() (WooCommerce way)

    $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>';
    }
    

    Both ways work.