I've googled extensively and tried my best, but I just can't get the first level children of the custom taxonomy in the code below to work! It only displays the parent level. What I am trying to achieve is the following:
Level 1 <--- at the moment, it only displays this level
Level 2 <-- I want to display this level too
Level 3 <-- but NOT this level
This is my code so far:
function my_dropdown_categories( $taxonomy, $current_selected = '', $include = null ) {
// Get all terms of the chosen taxonomy
$terms = get_terms($taxonomy, array('orderby' => 'name'));
// our content variable
$list_of_terms = '<select id="location" class="selectboxSingle" name="location">';
if ( ! is_wp_error( $terms ) ) foreach($terms as $term){
// If include array set, exclude unless in array.
if ( is_array( $include ) && ! in_array( $term->slug, $include ) ) continue;
$select = ($current_selected == $term->slug) ? "selected" : ""; // Note: ==
if ($term->parent == 0 ) {
// get children of current parent.
// $tchildren = get_term_children($term->term_id, $taxonomy); <- gets ALL children
$uchildren =get_terms( $taxonomy, array('hide_empty' => 0, 'parent' => $term->term_id ));
$children = array();
foreach ($uchildren as $child) {
$cterm = get_term_by( 'id', $child, $taxonomy );
// If include array set, exclude unless in array.
if ( is_array( $include ) && ! in_array( $cterm->slug, $include ) ) continue;
$children[$cterm->name] = $cterm;
}
ksort($children);
// PARENT TERM
if ($term->count > 0) {
$list_of_terms .= '<option class ="group-result" value="'.$term->slug.'" '.$select.'>' . $term->name .' </option>';
} else {
$list_of_terms .= '<option value="'.$term->slug.'" '.$select.'>'. $term->name .' </option>';
};
// now the CHILDREN.
foreach($children as $child) {
$select = ($current_selected == $child->slug) ? "selected" : ""; // Note: child, not cterm
$list_of_terms .= '<option class="result-sub" value="'.$child->slug.'" '.$select.'>'. $child->name.' </option>';
} //end foreach
}
}
$list_of_terms .= '</select>';
return $list_of_terms;
}
If someone can help me with this beast, you'll be my freaken hero!
EDIT (more info based on Pieter's answer):
This is what is being output (all parents):
Parent 1
--Parent 1
--Parent 2
--Parent 3
--Parent 4
Parent 2
--Parent 2
--Parent 1
--Parent 3
etc
// OPTGROUP FOR PARENTS
code is freaking me out, are you using braces or not? Seems like some horrible to read mix. My advice would be to get all the{}
in and update the question. Also test it after converting to the explicit form to see if this fixes some small problem.$include
? What if onlycontinue
happens in that loop? Also, is'parent' => 1
intentional or you are assuming it to be a boolean value (0/1). Shouldn't it be'parent' => $term->id
?