我想在注册表中显示用户角色的选择框。我正在使用此模型:
/* ROLES IN LIST REGISTRATION */
// 1. Add a new form element...
add_action( \'register_form\', \'odin_register_form\' );
function odin_register_form() {
global $wp_roles;
echo \'<select name="role" class="input">\';
echo \'<option disabled selected value> -- </option>\';
foreach ( $wp_roles->roles as $key=>$value ):
echo \'<option value="\'.$key.\'">\'.$value[\'name\'].\'</option>\';
endforeach;
echo \'</select>\';
}
// 2. Add validation.
add_filter( \'registration_errors\', \'odin_registration_errors\', 10, 3 );
function odin_registration_errors( $errors, $sanitized_user_login, $user_email ) {
if (
empty( $_POST[\'role\'] ) || ! empty( $_POST[\'role\'] ) && trim( $_POST[\'role\'] ) == \'\'
|| $_POST[\'role\'] == \'administrator\'
|| $_POST[\'role\'] == \'editor\'
|| $_POST[\'role\'] == \'contributor\'
|| $_POST[\'role\'] == \'author\'
|| $_POST[\'role\'] == \'shop_manager\'
) {
$errors->add( \'role_error\', __( \'<strong>ERROR</strong>: Select a valid option.\', \'odin\' ) );
}
return $errors;
}
//3. Finally, save our extra registration user meta.
add_action( \'user_register\', \'odin_user_register\' );
function odin_user_register( $user_id ) {
if (
$_POST[\'role\'] != \'administrator\' ||
$_POST[\'role\'] != \'editor\' ||
$_POST[\'role\'] != \'contributor\' ||
$_POST[\'role\'] != \'shop_manager\' ||
$_POST[\'role\'] != \'author\'
) {
$user_id = wp_update_user( array( \'ID\' => $user_id, \'role\' => $_POST[\'role\'] ) );
}
}
关键是,我没有看到验证选择空选项时发生的错误。
因此,我的想法如下:
1) 过滤除管理员、编辑、作者、参与者和商店经理之外的用户类型。我可以只设置订阅服务器和客户功能,但项目必须可以自由创建其他角色,而无需再次编写代码。
2) 我需要验证此字段中选项的记录,因为它已经实现了选择列表中角色的过滤呈现,我们必须确保有可能在html中插入一个值为“administrator”的选项。这可能不会发生在任何具有某种编辑能力的论文上。
我需要你告诉我怎么做。
SO网友:majick
我想!isset 是一种更可靠的测试方法,因此我补充道:
add_filter( \'registration_errors\', \'odin_registration_errors\', 10, 3 );
function odin_registration_errors( $errors, $sanitized_user_login, $user_email ) {
if (
!isset( $_POST[\'role\'] )
|| empty( $_POST[\'role\'] )
|| trim( $_POST[\'role\'] ) == \'\'
|| $_POST[\'role\'] == \'administrator\'
|| $_POST[\'role\'] == \'editor\'
|| $_POST[\'role\'] == \'contributor\'
|| $_POST[\'role\'] == \'author\'
|| $_POST[\'role\'] == \'shop_manager\'
) {
$errors->add( \'role_error\', __( \'<strong>ERROR</strong>: Select a valid role option.\', \'odin\' ) );
}
// debug $error to file
$debugfile = get_stylesheet_directory().\'/roledebug.txt\';
ob_start(); print_r($errors); $debugdata = ob_get_contents();
file_put_contents($debugfile,$debugdata); ob_end_clean();
return $errors;
}
我不确定,但可能会改变
<select> 要素
selected 把某事归因于某人
selected="selected" 在第一个函数中也是。