I have been trying to wrap my head around a issue for the past 2 days but despite trying all I could, I can't seem to reach the solution.
On the backend, I have a hierarchical taxonomy named "Programs" for the user object. The hierarchy is as follows:
Parent
-- Child
--- Grand Child
I have a frontend user settings form where I'm outputting the terms of this taxonomy using the following code:
$args = array('hide_empty' => false, 'hierarchical' => true, 'parent' => 0);
$terms = get_terms("program", $args);
$fieldName = "programs";
$html = '';
$html .= '<select name="' . $fieldName . '"' . 'class="programs"' . '>';
foreach ( $terms as $term ) {
$selected = $terms[0]->term_id;
$html .= "<option value='".$term->term_id."'".($selected == $term->term_id ? ' selected="selected"' : '').">" . $term->name . '</option>';
$args = array(
'hide_empty' => false,
'hierarchical' => true,
'parent' => $term->term_id
);
$childterms = get_terms("program", $args);
foreach ( $childterms as $childterm ) {
$selected = $childterms[0]->term_id;
$html .= "<option value='".$term->term_id."'".($selected == $childterm->term_id ? ' selected="selected"' : '').">" . $term->name . ' > ' . $childterm->name . '</option>';
$args = array('hide_empty' => false, 'hierarchical' => true, 'parent' => $childterm->term_id);
$granchildterms = get_terms("program", $args);
foreach ( $granchildterms as $granchild ) {
$selected = $granchildterms[0]->term_id;
$html .= "<option value='".$term->term_id."'".($selected == $granchild->term_id ? ' selected="selected"' : '').">" . $term->name . ' > ' . $childterm->name . ' > ' . $granchild->name . '</option>';
}
}
}
$html .= "</select>";
echo $html;
This code outputs the following HTML and although when I submit the form, the correct taxonomy term is getting saved in the database, the frontend form always shows "Grand Child 1" as selected, even if "parent" or "child" is set in the database. I also see the first 3 options are getting set as selected while only one should be set as selected at any given time :
<select name="programs" class="programs">
<option value="6" selected="selected">Parent</option>
<option value="7" selected="selected">Parent > Child 1</option>
<option value="8" selected="selected">Parent > Child 1 > Grand Child 1</option>
<option value="9">Child 2</option>
</select>
Here is a dump of the $terms (parent) variable:
Array
(
[0] => stdClass Object
(
[term_id] => 6
[name] => Parent
[slug] => parent
[term_group] => 0
[term_taxonomy_id] => 6
[taxonomy] => program
[description] =>
[parent] => 0
[count] => 0
)
)
1
Kindly help! Thanks a lot!