函数文档

checked()

💡 云策文档标注

概述

checked() 函数用于输出 HTML 的 checked 属性,通过比较两个参数值是否相同来决定是否标记为选中状态。它是 WordPress 开发中处理表单复选框和单选按钮的常用辅助函数。

关键要点

  • 函数原型:checked( $checked, $current = true, $display = true ),返回 HTML 属性字符串或空字符串
  • 核心功能:比较 $checked 和 $current 参数,若相同则输出 checked="checked",否则输出空字符串
  • 参数说明:$checked 为必需值,$current 默认为 true,$display 控制是否直接回显(默认 true)
  • 内部实现:基于 __checked_selected_helper() 私有辅助函数,与 selected()、disabled() 等函数共享逻辑
  • 应用场景:广泛用于 WordPress 后台设置、小部件表单、自定义控件等界面元素的选中状态处理

代码示例

// 使用 if 语句测试值
<input type="checkbox" name="test" value="1" <?php if ( 1 == $value ) echo 'checked="checked"'; ?> />

// 使用 checked() 函数替代
<input type="checkbox" name="test" value="1" <?php checked( $value, 1 ); ?> />

注意事项

  • 选项保存问题:复选框未选中时可能不保存值,使用前应检查选项是否设置,例如通过 isset() 或设置默认值
  • 多选复选框处理:对于多选场景,checked() 函数可接受数组作为参数进行比较,确保正确输出选中状态

📄 原文内容

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

Version Description
1.0.0 Introduced.

User Contributed Notes

  1. Skip to note 4 content

    Example

    
    <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.

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