函数文档

selected()

💡 云策文档标注

概述

selected() 是 WordPress 核心函数,用于输出 HTML 的 selected 属性。它通过比较两个参数,若相同则标记为选中状态,常用于生成下拉菜单选项。

关键要点

  • 函数原型:selected( $selected, $current = true, $display = true ),返回字符串或直接输出。
  • 参数说明:$selected 为必需值,用于比较;$current 可选,默认为 true;$display 控制是否回显,默认为 true。
  • 内部实现:调用 __checked_selected_helper() 辅助函数,处理 selected、checked、disabled 和 readonly 属性。
  • 应用场景:广泛用于 WordPress 后台和前端,如评论类型下拉、语言选择器、页面模板下拉等。

代码示例

// 示例:在循环中生成下拉选项,使用 selected() 标记当前选中项
foreach ( $posts as $post ) {
    echo '<option value="' . esc_attr( $post->ID ) . '"'
         . selected( $selected_id, $post->ID, false ) . '>'
         . esc_html( $post->post_title ) . '</option>';
}

注意事项

  • 当在 sprintf 或字符串拼接中使用时,需将 $display 参数设为 false 以返回字符串而非直接输出。
  • 确保参数类型匹配,避免比较错误;函数基于值相等性判断,不进行类型转换。

📄 原文内容

Outputs the HTML selected attribute.

Description

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

Parameters

$selectedmixedrequired
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 selected( $selected, $current = true, $display = true ) {
	return __checked_selected_helper( $selected, $current, $display, 'selected' );
}

Changelog

Version Description
1.0.0 Introduced.

User Contributed Notes

  1. Skip to note 4 content

    Example

    <!-- Testing the values with if() -->
    <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>
     
    <!-- Using selected() instead -->
    <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. Skip to note 5 content

    Selected Using foreach loop

    /**
     * Demonstration uses all cpt posts in a dropdown field to select 
     * a featured listings to callback in a function
     */
    function wporg_wpselected_featured_listing_cb()
    {
    
        $post_type = 'wpselected_post';
        $options   = get_option( 'wpselected_lists' );
    
        // select(ed)_id will be a custom option outside of this function.
        $wpselected_select_id = $options['wpselected_featured_listing'];
    
        // Avoid ending up with no string value by setting a default value
        if ( '' === $wpselected_select_id ) {
            $wpselected_select_id = 0; 
        }
    
        /**
         * Sets up a list of cpt posts to do foreach with
         * @param $label string Optional
         */
        $post_type_object = get_post_type_object( $post_type );
        $label = $post_type_object->label;
        $posts = get_posts( array(
                'post_type'         => $post_type, 
                'post_status'       => 'publish', 
                'suppress_filters'  => false, 
                'posts_per_page'    => -1
        ) );
        ?>
        <label class="olmin"></label>
        <select name="wpselected_lists[wpselected_featured_listing]">
        <option value="0"></option>
        ID ) . '"' 
                 . selected( $wpselected_select_id, $post->ID, false ) . '>' 
                 . esc_html__( $post->post_title, 'wpselected' ) . '</option>';   
        }
        echo '</select>';  
    } 

    Ideally you may choose to use ob_start() and ob_get_clean() to avoid any HTML glitches on front.

  3. Skip to note 6 content

    If you’re going to use this in a sprintf or string function, make sure you turn the echo parameter to false (so it returns a string instead of outputting directly) like so:

    // Defined options
    define( 'OPTIONS',  array( 1 => 'A', 2 => 'B', 3 => 'C', 4 => 'D' ) );
    
    // My option
    $my_option  = 1; // OR fetched option value
    
    // Get HTML options
    $html_options = '';
    foreach ( OPTIONS as $key => $value ) {
    	$html_options .= sprintf(
    		'<option value="%1$s" %3$s>%2$s</option>',
    		esc_attr( $key ),
    		esc_html( $value ),
    		<strong>selected( $my_option, esc_attr( $key ), false )</strong>
    	);
    }
    
    // Display Select element or tag
    echo '<select>' . $html_options . '</select>';