I’m using the WordPress selected()
function to display the current option in a dropdown list. The issue I am having is that for some reason WordPress is printing out selected='selected'
above the form in addition to in the actual <option>
elements. This is how I am using the selected()
function.
<select name="gender">
<option value="male" " . selected( $values['gender'] , 'male') . ">Male</option>
<option value="female" " . selected( $values['gender'] , 'female') . ">Female</option>
<option value="other" " . selected( $values['gender'] , 'other') . ">Other</option>
</select>
Removing the markup above eliminates the selected='selected'
which is appearing completely outside of the <form>
element.
2 Answers
The selected function causes immediate output, it does not return a string. Therefore you can’t use it like that, in a string building mode.
If you want it to return a string instead of immediately outputting the text, pass false to the $echo parameter.
$string = "
<select name="gender">
<option value="male" " . selected( $values['gender'] , 'male', false) . ">Male</option>
<option value="female" " . selected( $values['gender'] , 'female', false) . ">Female</option>
<option value="other" " . selected( $values['gender'] , 'other', false) . ">Other</option>
</select>
";