checked( mixed $checked, mixed $current = true, bool $display = true ): string

Outputs the HTML checked attribute.

Description

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

Parameters

$checkedmixedrequired
One of the values to compare.
$currentmixedoptional
The other value to compare if not just true.

Default:true

$displaybooloptional
Whether to echo or just return the string.

Default:true

Return

string HTML attribute or empty string.

Source

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

Changelog

VersionDescription
1.0.0Introduced.

User Contributed Notes

  1. Skip to note 4 content

    Example

    <?php // Get an array of options from the database. $options = get_option( 'slug_option' ); // Get the value of this option. $checked = $options['self-destruct']; // The value to compare with (the value of the checkbox below). $current = 1; // True by default, just here to make things clear. $echo = true; ?> <input name="slug-option[self-destruct]" value="1"	<?php checked( $checked, $current, $echo ); ?>/>

    Testing the value with if():

    <input type='checkbox' name='options[postlink]' value='1'	<?php if ( 1 == $options['postlink'] ) echo 'checked="checked"'; ?> />

    Using checked() instead:

    <input type="checkbox" name="options[postlink]" value="1"	<?php checked( $options['postlink'], 1 ); ?> />
  2. Skip to note 5 content
    Anonymous User

    Note that checking for

    checked()

    may/is not enough!

    Options are not saved if left empty (in the checkbox case == unchecked).

    Thus, before checked( $options['option_name'], 1 ); we should also check if the option is actually set, with something like:

    $options = get_option( 'wpdocs_option_array' ); if ( ! isset( $options['option'] ) ) { $options['option'] = 0; }
  3. Skip to note 6 content

    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( 1, $postlink ), 1); ?> /> <input type="checkbox" name="postlink[]" value="2" <?php checked(in_array( 2, $postlink ), 1); ?> /> <input type="checkbox" name="postlink[]" value="3" <?php checked(in_array( 3, $postlink ), 1); ?> />

You must log in before being able to contribute a note or feedback.