checked()
Outputs the html checked attribute.
Compares the first two arguments and if identical marks as checked.
1 time — 0.000001 sec (speed of light) | 50000 times — 0.01 sec (speed of light) | PHP 7.3.12, WP 5.3.2
No Hooks.
Return
String
. HTML attribute or empty string.
Usage
checked( $checked, $current, $echo );
- $checked(mixed) (required)
- One of the values to compare.
- $current(mixed)
- The other value to compare if not just true.
Default: true - $echo(true|false)
- Whether to echo or just return the string.
Default: true
Examples
#1 Demo
See what the function outputs depending on the input of different parameters.
checked( 1 ); // checked='checked' checked( 0 ); // '' checked( '1' ); // checked='checked' checked( '0' ); // '' checked( true ); // checked='checked' checked( false ); // '' checked( 1, '1' ); // checked='checked' checked( true, '1' ); // checked='checked' checked( true, 'str' ); // '' checked( 2 ); // '' checked( 'str' ); // '' checked( array() ); // '' checked( array(true) ); // '' checked( array(1) ); // ''
#2 Example of using checked() in code
<?php // get the option from the database. The option value is an array. $option = get_option('slug_option'); // Get the value of the option we need $checked = $option['self-destruct'] ?? false; // either true or 1 is expected here ?> <input name="slug_option[self-destruct]" value="1"<?php checked( $checked ); ?>/>
#3 Compare the PHP variant vs `checked()
Option with checked()
<input type="checkbox" name="options[postlink]" value="1"<?php checked( $options['postlink'] ); ?> >
Option with if()
<input type='checkbox' name='options[postlink]' value='1' <?php if ( 1 == $options['postlink'] ) echo 'checked="checked"'; ?> >
#4 Multiselect checkbox
For multiselect checkbox use array in checked function instead of simple value.
<?php $postlink = get_post_meta( $post->ID, 'postlink', true ); ?> <input type="checkbox" name="postlink[]" value="1" <?php checked( in_array( $postlink, 1 ), 1 ) ?> /> <input type="checkbox" name="postlink[]" value="2" <?php checked( in_array( $postlink, 2 ), 1 ) ?> /> <input type="checkbox" name="postlink[]" value="3" <?php checked( in_array( $postlink, 3 ), 1 ) ?> />
Changelog
Since 1.0.0 | Introduced. |
checked() checked code WP 6.1.1
function checked( $checked, $current = true, $echo = true ) { return __checked_selected_helper( $checked, $current, $echo, 'checked' ); }