SignIn with google WordPress – Plugin development
In this tutorial, we are going to create a simple WordPress plugin that allows you to signin with google to your website. Here is the demo of what we are going to create.
Demo
Table of content
- Creating and Activating the Plugin.
- Displaying Google One-tap Sign In Popup.
- Calling an AJAX in WordPress.
- Show Popup to Non-authenticated Users Only.
- Replace User Gravatar with Your Image.
Let’s get started
So let’s start allowing your users to signin with google on your WordPress website.
First, go to your wp-content content at the root of your WordPress website. And inside this, go to the plugins folder. Then create a new folder named signin-with-google. This will be our plugin folder, you are free to name it as you like.
Inside this newly created folder, create a new file named signin-with-google.php. This will be our main file. By setting the same name as the folder name, WordPress will automatically pick it up as the main file. Write the following code in this file to view it on the “Plugins” page in the admin panel.
<?php
/**
* Plugin Name: Sign in With Google
* Description: This plugin is for one-tap google sign in.
* Version: 1.0
* Author: adnan-tech.com
**/
Go to your “Plugins” page in your WordPress admin dashboard and you will see your plugin as “Sign in With Google”. You can find the direct link to the plugins folder from the following URL:
https://{your_domain}/wp-admin/plugins.php
You need to “Activate” your plugin in order to make it work.
Displaying google one-tap sign-in popup
To display the Google one-tap Sign-in popup on each page, you first need to generate a Google OAuth client ID. You can generate it from here. Or you can follow our tutorial that will help you set this up.
After the client ID is generated, write the following code in your plugin’s main file:
function SIWG_init()
{
// [user authentication is checked here]
// [JS scripts will be included here]
echo '<script src="https://accounts.google.com/gsi/client" async defer></script>
<div id="g_id_onload"
data-client_id="{your_google_client_id}"
data-context="signin"
data-callback="SIWG_googleLoginEndpoint"
data-close_on_tap_outside="false">
</div>';
}
add_action('wp_footer', 'SIWG_init');
Make sure to write your own Google Client ID in place of {your_google_client_id} code. Refresh your frontend side and open your browser console window. You will see an error that you need to create a Javascript function. So we will create a Javascript function that will be called when the user clicks the “Sign in” button on the popup.
So write the following code in the [JS scripts will be included here] section:
wp_register_script('custom_js', plugins_url('SIWG-script.js?v=1',__FILE__ ));
wp_enqueue_script('custom_js');
// [include WP util]
Then create the file named SIWG-script.js at the root of your plugin folder. We are appending “?v=1” at the end of the path of the file, it is to prevent the browser from caching this file. If you are making changes in your Javascript code and your changes are not being reflected when you refresh the page, simply increment the “?v=1” counter and it will work fine.
Following will be the code of SIWG-script.js file:
function SIWG_googleLoginEndpoint(googleUser) {
console.log(googleUser);
// [ajax code goes here]
}
Now refresh the page and this time there will be no error. Click the “Sign in” button in the popup and you will see the credential object in the browser console. On the client-side, Google only returns this credential also known as ID Token. We will send this ID Token to the server to verify the user.
Calling an AJAX in WordPress
To send an AJAX in WordPress, we need to include a built-in WordPress library called wp-util. So write the following code in the [include WP util] section:
// Manually enqueue the wp-util library.
wp_enqueue_script( 'wp-util' );
After that, we need to call an AJAX from Javascript. So replace the [ajax code goes here] section with the following code:
wp.ajax.post( "SIWG-google-login", {
"credential": googleUser.credential
} )
.done(function(response) {
console.log(response);
window.location.reload();
})
.fail(function (response) {
console.error(response);
});
Now we need to create an API in our plugin’s main PHP file that will handle this request.
// a function that will handle the AJAX request
function SIWG_google_login()
{
// secure credential value from AJAX
$credential = sanitize_text_field($_POST["credential"]);
// verify the ID token
$curl = curl_init( 'https://oauth2.googleapis.com/tokeninfo?id_token=' . $credential );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
$response = curl_exec( $curl );
curl_close( $curl );
// convert the response from JSON string to object
$response = json_decode($response);
// if there is any error, send the error back to client
if (isset($response->error))
{
wp_send_json_error($response->error_description);
}
else
{
// check if user already exists in WordPress users
$user_id = username_exists( $response->email );
if ( ! $user_id && !email_exists( $response->email ) )
{
// user does not exists
// generate a random hashed password
$random_password = wp_generate_password( $length = 12, $include_standard_special_chars = false );
// insert the user as WordPress user
$user_id = wp_insert_user([
"user_email" => $response->email,
"user_pass" => $random_password,
"user_login" => $response->email,
"display_name" => $response->name,
"nickname" => $response->name,
"first_name" => $response->given_name,
"last_name" => $response->family_name
]);
}
// do login
$user = get_user_by('login', $response->email );
if ( !is_wp_error( $user ) )
{
wp_clear_auth_cookie();
wp_set_current_user ( $user->ID );
wp_set_auth_cookie ( $user->ID );
// set user profile picture
update_user_meta($user->ID, "SIWG_profile_picture", $response->picture);
}
// send the success response back
wp_send_json_success( $response );
}
}
add_action( 'wp_ajax_nopriv_SIWG-google-login', 'SIWG_google_login' );
Comments have been added with each line for an explanation. Refresh the page now and when the popup is displayed, click on the “Sign in” button. Your browser page will refresh automatically after a few seconds. And you will see that the user is now logged-in.
You can also see the user in the admin panel dashboard.
Show popup to non-authenticated users only
Users who are already logged in to your site should not be seeing the popup as they are already logged in. So we need to show this popup only for users who are not logged in. So write the following code in the [user authentication is checked here] section:
if (is_user_logged_in())
{
return false;
}
It will simply stop the function from executing if the user is already logged in.
Replace user gravatar with your image
We are saving the user profile picture URL from google in our user metadata using the key “SIWG_profile_picture“. Now we need to display it. To do that, we need to add a filter that will update the WordPress Gravatar image with the URL saved in the database. Add the following code in your plugin’s main PHP file.
function SIWG_override_avatar( $avatar, $id_or_email, $size, $default, $alt )
{
//If is email, try and find user ID
if( ! is_numeric( $id_or_email ) && is_email( $id_or_email ) )
{
$user = get_user_by( 'email', $id_or_email );
if( $user )
{
$id_or_email = $user->ID;
}
}
//if not user ID, return
if( ! is_numeric( $id_or_email ) )
{
return $avatar;
}
//Find URL of saved avatar in user meta
$saved = get_user_meta( $id_or_email, 'SIWG_profile_picture', true );
//check if it is a URL
if( filter_var( $saved, FILTER_VALIDATE_URL ) )
{
//return saved image
return '<img src="' . esc_url( $saved ) . '" alt="' . esc_attr( $alt ) . '" />';
}
//return normal
return $avatar;
}
add_filter( 'get_avatar', 'SIWG_override_avatar', 10, 5 );
By adding the above code, if the user is logged-in and is registered by Google, then his profile picture will be displayed as in his google account. Otherwise, it will be displayed by WordPress gravatar.
So that’s how you can enable your site’s visitors to signin with google on your wordpress website. This will definitely increase the number of daily registrations. Because it is a quicker way for the users to join.