I am trying to create a custom login functionality in WordPress. What I need is instead of using the default user_pass
field in the wp_users
table I want to use a custom user meta value from the wp_usermeta
table. I know there is a authenticate
filter hook in WordPress which can be used to write a custom authentication function. The problem is that the authentication I need is for the WordPress APIs. I will be using another application to access WordPress using the APIs. So after a user is authenticated then he can create/edit/delete posts. There is a plugin available for API authentication called WP OAuth Server. But that uses client id or username/password for authentication. Is there a way I can use the filter hook on this plugin? Or create a custom function for authenticating the user through APIs?
I was able to achieve it by using the plugin JWT Authentication for WP REST API. The plugin supports authentication for WordPress API using username and password. So I used the authenticate
filter to use my own custom login function.
function custom_auth_signon($user, $username, $password) {
global $wpdb;
$user_details = get_user_by('login', $username);
$query = $wpdb->prepare("SELECT user_id FROM {$wpdb->prefix}usermeta WHERE user_id = " . $user_details->data->ID . " AND meta_key = 'custom_password' AND meta_value = %s", $password);
$result = $wpdb->get_results($query);
if ($result[0]->user_id) {
return $user_details;
} else {
return NULL;
}
}
add_filter('authenticate', 'custom_auth_signon', 30, 3);