从Foreach中选择带有两个选项的下拉列表

时间:2016-12-27 作者:Bart

我有个问题。我只需要列出两个角色:客户和shop\\u经理。1、我怎样才能用这个脚本做到这一点?

add_action( \'register_form\', \'myplugin_register_form\' );
function myplugin_register_form() {

    global $wp_roles;

    echo \'<select name="role" class="input">\';
    foreach ( $wp_roles->roles as $key=>$value ):
       echo \'<option value="\'.$key.\'">\'.$value[\'name\'].\'</option>\';
    endforeach;
    echo \'</select>\';

}

2 个回复
最合适的回答,由SO网友:Tunji 整理而成

您可以使用in_array 检查角色的名称是customer还是shop\\u manager

add_action(\'register_form\', \'myplugin_register_form\');
function myplugin_register_form() {

    global $wp_roles;

    echo \'<select name="role" class="input">\';
    foreach ($wp_roles->roles as $key => $value):
        if ( in_array( $key, array(\'customer\', \'shop_manager\') ) )
            echo \'<option value="\' . $key . \'">\' . $value[\'name\'] . \'</option>\';
    endforeach;
    echo \'</select>\';

}

SO网友:Bart

因此,请遵循主题。这是Wordpress中注册页面中添加选择角色的代码。

//1. Add a new form element...
add_action(\'register_form\', \'myplugin_register_form\');
function myplugin_register_form() {

    global $wp_roles;

    echo \'<select name="role" class="input">\';
    foreach ($wp_roles->roles as $key => $value):
        if ( in_array( $key, array(\'customer\', \'shop_manager\') ) )
            echo \'<option value="\' . $key . \'">\' . $value[\'name\'] . \'</option>\';
    endforeach;
    echo \'</select>\';

}

//2. Add validation.
add_filter( \'registration_errors\', \'myplugin_registration_errors\', 10, 3 );
function myplugin_registration_errors( $errors, $sanitized_user_login, $user_email ) {

    if ( empty( $_POST[\'role\'] ) || ! empty( $_POST[\'role\'] ) && trim( $_POST[\'role\'] ) == \'\' ) {
         $errors->add( \'role_error\', __( \'<strong>ERROR</strong>: You must include a role.\', \'mydomain\' ) );
    }

    return $errors;
}

//3. Finally, save our extra registration user meta.
add_action( \'user_register\', \'myplugin_user_register\' );
function myplugin_user_register( $user_id ) {

   $user_id = wp_update_user( array( \'ID\' => $user_id, \'role\' => $_POST[\'role\'] ) );
}