Sorting Attributes order when using get_the_terms

This code has worked to display product attributes on a page.

How do I sort/order them by slug? They are currently sorted by name.

 global $post;
 $terms = get_the_terms( $post->ID, 'pa_size');
 foreach ( $terms as $term ) {
 echo "<li>" .$term->name. "</li>";
 }

Solutions Collecting From Web of "Sorting Attributes order when using get_the_terms"

You will need to sort them yourself:

 $terms = get_the_terms( $post->ID, 'category');
 foreach ( $terms as $term ) {
  $newterms[$term->slug] = $term;
 }
 ksort($newterms);
 foreach ( $newterms as $term ) {
  echo "<li>" .$term->name. "</li>";
 }

Or, if you feel adventurous, the same with a filter:

function alpha_sort_terms($terms) {
  remove_filter('get_the_terms','alpha_sort_terms');
  foreach ( $terms as $term ) {
    $newterms[$term->slug] = $term;
  }
  ksort($newterms);
  return $newterms;
}
add_filter('get_the_terms','alpha_sort_terms');

$terms = get_the_terms( $post->ID, 'category');
foreach ( $terms as $term ) {
  echo "<li>" .$term->name. "</li>";
}