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.
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.
Where are your PHP tags?
Unless you’re somehow wrapping the whole thing in an echo that isn’t displayed in your code snippet?
Also, probably entirely a matter of personal preference, but I always put HTML attributes in double-quotes, and PHP attributes in single quotes, in order to help avoid mixing them up in mixed PHP/HTML markup.