Change user role via URL [WordPress]

好久不见. 提交于 2020-03-21 05:44:43

问题


I'm creating plugin which will register all new users as role = unverified and stop user from login until email verification. I want to send url on their email which will change the current unverified role to author. I know how to send email etc all of that in WordPress but can't figure out how to create url which will change the role. I'm using custom ajax form to login,register and lostpassword because of it i'm unable to use pie register and register-plus-redux plugins.

Current code

function add_roles_on_plugin_activation() {
    add_role( 'custom_role', 'Unverified', array( 'read' => true, 'level_0' => true ) );
}
register_activation_hook( __FILE__, 'add_roles_on_plugin_activation' ); 

function remove_roles_on_plugin_deactivation() {
    remove_role( 'custom_role' );
}
register_deactivation_hook( __FILE__, 'remove_roles_on_plugin_deactivation' ); 

add_filter('pre_option_default_role', function($default_role){
    return 'custom_role'; 
    return $default_role; 
});


function error_email_verify() {
$user = wp_get_current_user();
if ( in_array( 'custom_role', (array) $user->roles ) ) {

       $logout_url = wp_login_url().'?mode=emailverify';
       wp_logout();
       wp_redirect( $logout_url );
       exit();
    }     
}
add_action('wp_loaded', 'error_email_verify');

function my_login_message() {

    if( $_GET['mode'] == 'emailverify' ){
        $message = '<p id="login_error"><b>Verify your email.</b></p>';
        return $message;
    }

}
add_filter('login_message', 'my_login_message');

回答1:


Here is what I would do. Basically I would generate a link that would have parameters attached to it something like this:

Generate Link

$username = 'user_login';
$hashcode = sha1(md5(md5("hacaak".$username."aalog")));
$link = get_home_url().'/?a='.$hashcode.'&b='.$hashcode.'&u='.$username.'&c='.$hashcode.'';


Output of link

[http:yourwebsite.com/a=fe440709d341e7b4994636b12e556aa7f23bb9ce&b=fe440709d341e7b4994636b12e556aa7f23bb9ce&u=jack&c=fe440709d341e7b4994636b12e556aa7f23bb9ce][1]

When the user clicks on this link in the email you just sent them use this method to catch the GET parameter coming into the site:

function to get the variables from url

function catch_email(){
    if(isset($_GET['a']))
    {
        $username = sanitize_user($_GET['u']);
        $user=get_user_by( 'login', $username );
        $user_id = $user->ID;
        $user_role = new WP_User($user_id);
        $user_role->remove_role( 'unverified' );
        $user_role->add_role( 'author' );
        $url = get_home_url().'/Login?mode=emailverify';
        wp_redirect($url);
    }
}

add_action('get_header', 'catch_email');


来源:https://stackoverflow.com/questions/32081574/change-user-role-via-url-wordpress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!