selected()WP 1.0.0

Outputs the html selected attribute.

Compares the first two arguments and if identical marks as selected.

No Hooks.

Return

String. HTML attribute or empty string.

Usage

selected( $selected, $current, $display );
$selected(mixed) (required)
One of the values to compare.
$current(mixed)
The other value to compare if not just true.
Default: true
$display(true|false)
Whether to echo or just return the string.
Default: true

Examples

0

#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>
0

#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 ); ?> />
0

#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() code WP 6.7.1

function selected( $selected, $current = true, $display = true ) {
	return __checked_selected_helper( $selected, $current, $display, 'selected' );
}