wp_dropdown_roles()
云策文档标注
概述
wp_dropdown_roles() 函数用于生成用户角色选择器的 HTML option 元素,便于在表单中创建下拉菜单。它接受一个可选参数来预设选中的角色。
关键要点
- 函数输出 HTML option 元素,适用于角色选择器。
- 参数 $selected 为字符串,可选,用于指定已选中角色的 slug。
- 内部使用 get_editable_roles() 获取可编辑角色列表,并通过 translate_user_role() 翻译角色名称。
- 常用于后台用户管理界面,如 WP_Users_List_Table::extra_tablenav() 中。
代码示例
// 示例:创建下拉菜单,默认选中“Editor”角色
wp_dropdown_roles( 'editor' );
原文内容
Prints out option HTML elements for role selectors.
Parameters
$selectedstringrequired-
Slug for the role that should be already selected.
Source
function wp_dropdown_roles( $selected = '' ) {
$r = '';
$editable_roles = array_reverse( get_editable_roles() );
foreach ( $editable_roles as $role => $details ) {
$name = translate_user_role( $details['name'] );
// Preselect specified role.
if ( $selected === $role ) {
$r .= "nt<option selected='selected' value='" . esc_attr( $role ) . "'>$name</option>";
} else {
$r .= "nt<option value='" . esc_attr( $role ) . "'>$name</option>";
}
}
echo $r;
}
Changelog
| Version | Description |
|---|---|
| 2.1.0 | Introduced. |
Skip to note 2 content
Codex
Example
If you would like to set a default role for the dropdown, provide the slug for the desired role as a parameter. The following example creates a dropdown of user roles with the “Editor” role as the default, selected value:
<select> </select>