I am retrieving taxonomy terms. The code is working.
Foreach creates three options for the select tag. There are three terms. But, when I wanted to echo "selected" for each options, after selecting one. it returns odd result. What is the problem?
Here is the code.
$terms = get_terms( 'department' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
echo '<select class="widefat" name="departments">';
foreach ( $terms as $term ) {
echo '<option value="'. $term->name .'"'.($_POST['departments'] == $term->name) ? ' selected="selected" ' : ''.'>'. $term->name . '</option>';
}
echo '</select>';
}
Returns this:
<select class="widefat" name="departments"> selected="selected" selected="selected" selected="selected" </select>
Custom post name: employee Taxonomy name: department There are three terms available: Web Designer, Web Developer, Graphics Designer
I am getting the taxonomy terms if I use this code.
$terms = get_terms( 'department' );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
echo '<select class="widefat" name="departments">';
foreach ( $terms as $term ) {
$value = $term->name;
for ($i=0; $i < count($term); $i++) {
echo '<option value="'
. $value .'"'.'>'
. $value . '</option>';
}
}
echo '</select>';
Returns:
<select class="widefat" name="departments">
<option value="Graphic Designer">Graphic Designer</option>
<option value="Web Designer">Web Designer</option>
<option value="Web Devloper">Web Devloper</option>
</select>
But if I want to implement selected into the selected option then it is collapsing.
I want to add if you chose Graphic Designer then the option would look like
<option value="Graphic Designer" selected="selected">Graphic Designer</option>
But this is not happening.