I am writing custom WordPress script which is supposed to show all custom taxonomies in element. Some of these elements have children, others don’t. Here is the code for the form:
<?php
$terms = get_terms("location", "hide_empty=0");
$count = count($terms);
if ( $count > 0 ){
foreach ( $terms as $term ) {
echo "<option value='" . $term->slug . "'>" . $term->name ."</option>";
}
}
echo "</select>";
The problem is, it shows all the elements in alphabetical order, both parents and children. I want children to be nested below the parents but I am not able to figure out how. Can anyone offer some help?
Here is print_r of the $terms array:
Array
(
[0] => stdClass Object
(
[term_id] => 18
[name] => Andrijevica
[slug] => andrijevica
[term_group] => 0
[term_taxonomy_id] => 18
[taxonomy] => location
[description] =>
[parent] => 0
[count] => 0
)
[1] => stdClass Object
(
[term_id] => 19
[name] => Berane
[slug] => berane
[term_group] => 0
[term_taxonomy_id] => 19
[taxonomy] => location
[description] =>
[parent] => 0
[count] => 0
)
[2] => stdClass Object
(
[term_id] => 17
[name] => Bijelo Polje
[slug] => bijelo-polje
[term_group] => 0
[term_taxonomy_id] => 17
[taxonomy] => location
[description] =>
[parent] => 0
[count] => 0
)
.....
[29] => stdClass Object
(
[term_id] => 53
[name] => Pobrežje
[slug] => pobrezje
[term_group] => 0
[term_taxonomy_id] => 63
[taxonomy] => location
[description] =>
[parent] => 4
[count] => 0
)
[30] => stdClass Object
(
[term_id] => 4
[name] => Podgorica
[slug] => podgorica
[term_group] => 0
[term_taxonomy_id] => 4
[taxonomy] => location
[description] =>
[parent] => 0
[count] => 7
)
As you can see parent is 0 for parents. Children have parent value set to term_id of the parent. For example [30] is parent of [29].
use
get_term_children()
inside the loop .Example :
sorry, the example is cut and paste from one of my projects and will create a nested UL.. if you need it for a dropdown options – well – I am sure you can modify it for your needs..