Using the WordPress selected() function

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.

Related posts

Leave a Reply

2 comments

  1. 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>
    ";
    
  2. Where are your PHP tags?

    <select name="gender">
    <option value="male" <?php selected( $values['gender'] , 'male'); ?>>Male</option>
    <option value="female" <?php selected( $values['gender'] , 'female'); ?>>Female</option>
    <option value="other" <?php selected( $values['gender'] , 'other'); ?>>Other</option>         
    </select>
    

    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.