How to Auto Login After Registration in WordPress with core php

后端 未结 3 1178
轻奢々
轻奢々 2020-12-23 11:11

I\'ve been trying for days now to take users who have just registered to my WordPress site and automatically log them in and then redirect them to a URL of my choice. By def

相关标签:
3条回答
  • 2020-12-23 11:18

    Following is based on how WooCommerce creates a new user and logs him in:

    $user_pass = esc_attr( $_POST['account_password'] );
    
    $new_user_data = array(
        'user_login' => $_POST['account_username'],
        'user_pass'  => $user_pass,
        'user_email' => $_POST['account_email'],
        'role'       => 'subscriber'
    );
    
    $user_id = wp_insert_user( $new_user_data );
    
    // Set the global user object
    $current_user = get_user_by( 'id', $user_id );
    
    // set the WP login cookie
    $secure_cookie = is_ssl() ? true : false;
    wp_set_auth_cookie( $user_id, true, $secure_cookie );
    

    to redirect use wp_safe_redirect, e.g.

    wp_safe_redirect( home_url( '/' ) );
    exit;
    
    0 讨论(0)
  • 2020-12-23 11:18

    Thanks for your support guys..i did on my own with the following code..thanks for your time and support :)

    <i>$getdetails= mysql_fetch_array(mysql_query("SELECT * FROM `wp_users` WHERE `ID`='$user_id'"));
    $username=$getdetails['user_login'];
    
    
    $creds = array();
    $creds['user_login'] = $username;
    $creds['user_password'] = $password;
    $creds['remember'] = true;
    
        $user = wp_signon( $creds, false );
        if ( is_wp_error($user) ){
            echo $user->get_error_message();
        }else{
            wp_redirect( home_url() );
        }
    
    0 讨论(0)
  • 2020-12-23 11:22

    // Add on function.php for Auto login after register and redirect to a home page. varified this code

    function auto_login_new_user( $user_id ) {
        wp_set_current_user($user_id);
        wp_set_auth_cookie($user_id);
        $user = get_user_by( 'id', $user_id );
        do_action( 'wp_login', $user->user_login );//`[Codex Ref.][1]
        wp_redirect( home_url() ); // You can change home_url() to the specific URL,such as "wp_redirect( 'http://www.wpcoke.com' )";
        exit;
    }
    add_action( 'user_register', 'auto_login_new_user' );
    
    0 讨论(0)
提交回复
热议问题