1

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>

1 Answer 1

4

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>
2
  • +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 Sep 19, 2014 at 6:21
  • Please accept your own answer :-) Feb 19, 2015 at 16:56

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.