Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have an array of objects with custom taxonomy terms. This taxonomy represents a list of countries/states/cities which are being used by a certain post type and other parameters (I'm not using a standard wp function to retrieve these).

The terms are already ordered alphabetically by term name key using usort.

I'm printing each term as an option within a select dropdown. What I'd like to do is to further organise the list by printing topmost terms as well as optgroup and put all child taxonomies inside as optgroup elements. The parent itself should be listed as a selectable option too. Only topmost parents should wrap children as options within optgroups.

Currently I'm just looping the terms as options without optgroups:

$locations = my_function(); // returns an array of alphabetically sorted wp term objects
echo '<select /*...mystuff...*/>';

foreach ( $locations as $location ) :
    echo '<option value="' . $location->slug . '">' . $location->name .  '</option>';

echo '</select>';
share|improve this question

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.