Woocommerce Attributes Pulling data in alpahabetic order

My Problem is trying to pull the size attributes for the different products. So, for that i used this php code

<?php 
        $terms = get_terms('pa_size');
        foreach ( $terms as $term ) {
        echo "<li>" .$term->name. "</li>";
         }
 ?>

The size attributes displaying for the above code should be in alphabetic order such as like L, M , S , XS instead of XS, S, L, M, XL, XXL. Help me out from these.

Related posts

Leave a Reply

2 comments

  1. Use asort()

    $terms = get_terms('pa_size');
    asort($terms);
    foreach ( $terms as $term ) {
            echo "<li>" .$term->name. "</li>";
    }
    

    For Testing purpose.

    $terms = array("XS","S","L","M","XL","XXL");
    echo '<pre>';print_r($terms);echo '</pre>';
    asort($terms);
    echo '<pre>';print_r(($terms));echo '</pre>';
    

    Demo

    array before sort

    <pre>Array
    (
        [0] => XS
        [1] => S
        [2] => L
        [3] => M
        [4] => XL
        [5] => XXL
    )
    </pre>
    

    array after sort

    <pre>Array
    (
        [2] => L
        [3] => M
        [1] => S
        [4] => XL
        [0] => XS
        [5] => XXL
    )
    </pre>
    
  2. Terms are ordered alphabetically by default however WooCommerce applies a filter which changes the ordering.

    To change the order back to alphabetical you need to set menu_order to false in your arguments for get_terms().

    Example:

    $terms = get_terms( 'pa_size', array(
        'menu_order' => false,
    ) );