I have the following code to list taxonomy terms in a drop down list. It works great, except the list in the drop down isn't in alphabetical order. How do I modify the code to list them alphabetically?

<form action="<?php bloginfo('url'); ?>/" method="get">
<?php
$term_id = 279;
$taxonomy_name = 'categories';
$termchildren = get_term_children( $term_id, $taxonomy_name );
echo '<select name="' . $taxonomy_name . '" onchange="this.form.submit()">';
echo '<option selected>Branding...</option>';
foreach ( $termchildren as $child ) {
    $term = get_term_by( 'id', $child, $taxonomy_name );
    $link = get_term_link( $child, $taxonomy_name );
    echo '<option value="'.$term->slug.'"><a href="' .esc_url( $link ) . '">' . $term->name . '</a></option>';
}
echo '</select>';
?> 
<noscript><div><input type="submit" value="View" /></div></noscript>
</form>

I found an answer to this at https://wordpress.stackexchange.com/a/105079/40536

I modified my code to the following:

<form action="<?php bloginfo('url'); ?>/" method="get">

<?php
$term_id = 279;
$taxonomy_name = 'categories';
$termchildren = get_term_children( $term_id, $taxonomy_name );
$children = array();
foreach ($termchildren as $child) {
  $term = get_term_by( 'id', $child, $taxonomy_name );
  $children[$term->name] = $term;
}
ksort($children);
echo '<select name="' . $taxonomy_name . '" onchange="this.form.submit()">';
echo '<option selected>Branding...</option>';
foreach ( $children as $child ) {
  $term = get_term_by( 'id', $child->term_id, $taxonomy_name );
  echo '<option value="'. $term->slug .'">' . $term->name . '</a></option>';
}
echo '</select>';
?> 
<noscript><div><input type="submit" value="View" /></div></noscript>

</form>
  • +1 for posting a solution to your own answer, and most importantly, adding the link as the source of your code. Just remember to return later to accept your own answer – Pieter Goosen Sep 19 '14 at 6:21
  • Please accept your own answer :-) – Pieter Goosen Feb 19 '15 at 16:56

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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