selected()
Outputs the string selected='selected' if the first two parameters of the function match.
Needed for use in the dropdown list <select>, in the <option> tag.
In dropdown lists, it is often necessary to check values and set the selected flag for the option that is currently set. This function was created for the convenience of such checks.
This is one of the helper functions for forms: checked(), disabled(), selected(), wp_readonly().
When comparing values, they are first converted to the same type (string), and then compared:
(string) $one === (string) $two
Thus, non-strict equality will still trigger, for example:
- int
1will be equal to string'1'. truewill be equal to1or'1'.falsewill be equal to0or'0'.- etc.
No Hooks.
Returns
String. The function outputs selected='selected' or an empty string ''.
If the last parameter $echo is false, the function will return the value instead of outputting it.
Usage
Usage
selected( $selected, $current, $display );
- $selected(string/int/bool) (required)
- First value to compare with the second.
- $current(string/int/bool)
- Second value to compare with the first.
Default: true - $display(bool)
- Output the value (true) or return for processing (false).
Default: true
Examples
#1 Compare selected() vs native PHP
PHP check:
<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>
The same check with selected()
<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>
#2 Using checked()
Routine check:
<input type='checkbox' name='options[postlink]' value='1' <?php if ( 1 == $options['postlink'] ) echo 'checked="checked"'; ?> />
Using checked()
<input type="checkbox" name="options[postlink]" value="1" <?php checked( $options['postlink'], 1 ); ?> />
#3 Using disabled() (since version 3.0)
<input type="radio" name="attachments" value="<?= $value ?>" <?php disabled( $value, false ) ?> />
It looks noticeably more compact.
Changelog
| Since 1.0.0 | Introduced. |
selected() selected code WP 7.0
function selected( $selected, $current = true, $display = true ) {
return __checked_selected_helper( $selected, $current, $display, 'selected' );
}