1

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>";
 }

1 Answer 1

4

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>";
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.