WordPress.org

Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/selected

Description

For use in select form fields. Compares two given values (for example, a saved option vs. one chosen in a form) and, if the values are the same, adds the selected attribute to the current option tag.

Usage

<?php selected( $selected, $current, $echo); ?>

Parameters

$selected
(mixed) (required) One of the values to compare.
Default: None
$current
(mixed) (optional) The other value to compare if not just true.
Default: true
$echo
(boolean) (optional) Whether to echo or just return the string.
Default: true

Returns

(string) 
HTML attribute (selected='selected') or empty string

Example

<!-- Testing the values with if() -->
<select name="options[foo]">
    <option value="1" <?php if ( $options['foo'] == 1 ) echo 'selected="selected"'; ?>>1</option>
    <option value="2" <?php if ( $options['foo'] == 2 ) echo 'selected="selected"'; ?>>2</option>
    <option value="3" <?php if ( $options['foo'] == 3 ) echo 'selected="selected"'; ?>>3</option>
</select>
 
<!-- Using selected() instead -->
<select name="options[foo]">
    <option value="1" <?php selected( $options['foo'], 1 ); ?>>1</option>
    <option value="2" <?php selected( $options['foo'], 2 ); ?>>2</option>
    <option value="3" <?php selected( $options['foo'], 3 ); ?>>3</option>
</select>

Changelog

Since: 1.0

Source File

selected() is located in wp-includes/general-template.php.

Related

checked(), disabled()