How to authenticate a wordpress user in external script

I’m attempting to check a user’s authentication in an external api file. I’m including the wp-load.php file and i’m receiving the following error:

Fatal error: Call to a member function add_query_var() on a non-object in /home/USERNAME/public_html/DOMAIN/wp-includes/rewrite.php on line 1834

Read More

Here’s my code:

function authentication ($user, $pass){

//Include wordpress files
require_once('/home/USERNAME/public_html/DOMAIN/wp-load.php');


if(empty($user) || empty($pass)){

    return false;

} else {
$auth = mysql_query("SELECT ID, user_login, user_pass FROM PREFIX_users WHERE user_login = '".$user."'");
$row = mysql_fetch_array($auth);
$uid = $row['ID'];


$status = false;

$auth = wp_authenticate($uid, $pass );

if( is_wp_error( $auth ) ) {        
    $status = false;
} else {
    $status = true;
}
return $status; 
}   

}

I removed the username, domain and prefix from this.

Related posts

Leave a Reply

1 comment

  1. For anyone else who finds this I simply had to add some global variables as well as passed a string username into wp_authenticate instead of the user id and finally included wp-blog-header.php instead of wp-load.php. Here is my final code:

    function authentication ($user, $pass){
      global $wp, $wp_rewrite, $wp_the_query, $wp_query;
    
      if(empty($user) || empty($pass)){
        return false;
      } else {
        require_once('/home/USERNAME/public_html/DOMAIN/wp-blog-header.php');
        $status = false;
        $auth = wp_authenticate($user, $pass );
        if( is_wp_error($auth) ) {      
          $status = false;
        } else {
          $status = true;
        }
        return $status;
      } 
    }