我想从wp_user表中获取用户ID。我写了以下代码,但是没有用

时间:2018-07-15 06:02:27

标签: php sql wordpress

我想要创建用户的代码(如果它不存在于db中并且工作正常),但是如果用户是真实的,那么我想授予对wordpress site.Control的访问权限在Else块中,但我无法提取电子邮件中的用户ID,以下代码写在else块中。我该怎么做?

if($bearer_token){

    global $wpdb;
    $name = $_POST['log'];
    $email = $_POST['log'];

    //$table_name = $wpdb->prefix . "wpuser";

    include_once(ABSPATH . '/var/www/html/wp-config.php');
    $connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
    $link = mysqli_select_db($connection, DB_NAME);
    if($link){
    //  echo "Success";
        ////////////////

        $db_name = $wpdb->prefix . "users";
       // echo $table_name;
        $wpdb->insert( $db_name, array(
            'name' => $name,
            'email' => $email
        ) );

        ///////////////
    }else{
        echo "Fail";
    }

}else{
    echo "Error";
}

//////////////////////////

if($bearer_token){
add_action( 'init', function () {

  $username = $_POST['log'];
  $password = $_POST['pwd'];
  $email_address = $_POST['log'];
  //$url = "0.0.0.0:8000"
//    echo "if inside";



  if ( ! username_exists( $username ) ) 

    {    
    $user_id = wp_create_user( $username, $password, $email_address );
    echo $user_id;
    $user = new WP_User( $user_id );
    $user->set_role( 'contributor' );

    }elseif (username_exists($username)==True) {
        // $user = get_user_by( 'user_email', $email_address );
        // $user = wp_get_current_user();
    $userdata = WP_User::get_data_by( 'user_login', $username );

    if ( !$userdata )
        return false;

    $user = new WP_User;
    $user->init( $userdata );

    return $user;

        # code...
    }else{
        echo "Errorrr";
    }
    }
   );
}else{
    echo "Unauthenticate user";
}

1 个答案:

答案 0 :(得分:0)

我不确定您是否决定如何区分用户的首次登录和同一用户的所有后续登录。但是,如果您想在每次遇到新电子邮件时都创建一个新用户,最简单的方法是将登录凭据传递给wp_authenticate($username, $password),您可以覆盖此凭据以执行自定义检查,如下所示:

add_action( 'wp_authenticate' , 'check_custom_authentication', 10, 2 );

function check_custom_authentication ( $username, $password ) {
        if ( ! username_exists( $username ) ) {
            return;
        }
        // use wp_set_password function here to set password by getting user id from the login detail we have.
}