Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

How to use google api for wordpress login

I’m also working on plugin which uses google oAuth and YouTube data API. The functionality works on backend, admin logs in just once using his gmail credentials and then with use of refresh_token we can keep him logged in.

Keep in mind the refresh token is generated only the first time you give access
to your app. You have to clear your permissions to fetch it
again.

I used PHP and not javascript, but still here is my complete function to give you a brief idea

<?php
public function uty_main_page(){
    require_once ('config.php');
    global $wpdb;
    if(isset($_GET['code'])) {
        $client->authenticate($_GET['code']);
        $_SESSION['token'] = $client->getAccessToken();
        $token_decode = json_decode($_SESSION['token']);
        update_option( 'uty_refresh_token' , $token_decode->refresh_token );
        $client->setAccessToken($_SESSION['token']);
        echo 'Authorization Successful';
    }
    ?>
                    <?php if(get_option( 'uty_refresh_token' ) != ''){ ?>
                        <li><a href="#uty_upload">Upload</a></li>
                        <li><a href="#uty_videos">All Videos</a></li>
                    <?php } ?>
                    <li><a href="#uty_settings">Settings</a></li>
                </ul>
            </div>
            <div class="tab_content">
                <?php if( $client->isAccessTokenExpired() ) { ?>
                    <?php if(get_option( 'uty_refresh_token' ) != ''){ ?>
                        <?php
                        $client->refreshToken( get_option( 'uty_refresh_token' ) );
                        $_SESSION['token'] = $client->getAccessToken();
                        $client->setAccessToken($client->getAccessToken());
                        ?>
                        <div id="uty_upload">
                            <?php
                            if(isset($_POST['uty_video_submit'])){
                                if(isset($_FILES['uty_video'])){
                                    $uploaded = media_handle_upload('uty_video', 0);
                                    if(is_wp_error($uploaded)){
                                        $message = $uploaded->get_error_message();
                                    }
                                    else{
                                            //Do Some coding here
                                    }
                                }
                            }
                            ?>
                        </div>
                    <?php } ?>
                <?php } ?>
                <div id="uty_settings">
                    <?php if(isset($_POST['revoke-access-token'])){ ?>
                        <?php update_option( 'uty_refresh_token' , '' ); ?>
                        <?php update_option( 'uty_google_client_api' , '' ); ?>
                        <?php update_option( 'uty_google_client_id' , '' ); ?>
                        <?php update_option( 'uty_google_client_secret' , '' ); ?>
                        <?php update_option( 'uty_youtube_channel' , '' ); ?>
                    <?php } ?>
                    <h3>Please enter the below details to kick start your Youtube uploads</h3>

                    <?php if( !empty(get_option('uty_google_client_api')) && !empty(get_option('uty_google_client_id')) && !empty(get_option('uty_google_client_secret')) && empty(get_option('uty_refresh_token')) ){ ?>
                            <?php $state = mt_rand(); ?>
                            <?php $client->setState($state); ?>
                            <?php $_SESSION['state'] = $state; ?>
                            <?php $authUrl = $client->createAuthUrl(); ?>
                            <a href="<?php echo $authUrl; ?>">Click here to authorize your credentials</a>
                    <?php } elseif( !empty(get_option('uty_google_client_api')) && !empty(get_option('uty_google_client_id')) && !empty(get_option('uty_google_client_secret')) && !empty(get_option('uty_refresh_token')) ){ ?>

                    <?php } ?>
                </div>
            </div>
        </div>
    </div>
<?php } ?>

In the above function the main thing i’ve done is to store refresh_token when user logs in first time and then pass it in function to get new access token every time.

$client->refreshToken( get_option( 'uty_refresh_token' ) );
$_SESSION['token'] = $client->getAccessToken();
$client->setAccessToken($client->getAccessToken());

These three lines does the work of getting new access token every time.
Hope this helps you

Related Posts:

  1. How to implement Google reCaptcha without installing a plugin?
  2. Custom Connect to Facebook, problem logging in/logging out
  3. What would be the best way to implement Magic Link logins in WordPress?
  4. For using google api is it necessary to install the google client libraries for using Oauth 2 in wordpress installation?
  5. WordPress Google Calendar Oath 404
  6. Best option to implement external register/login to WP from self-made API
  7. Google credentials and redirect URI for Google OAuth2 in a WordPress plugin, questions
  8. Get WordPress login functions without printing anything
  9. Set logged in user based on API response
  10. Login and register by API
  11. How to use WordPress REST API to login a user with dart/flutter?
  12. What is an Endpoint?
  13. Constructing requests with URL Query String in Python
  14. In Django, how do I know the currently logged-in user?
  15. Can I programmatically login a user without a password?
  16. Can’t log in: “ERROR: Cookies are blocked or not supported by your browser. You must enable cookies to use WordPress.”
  17. Is there any way to rename or hide wp-login.php?
  18. How to login with email only no username?
  19. How can I redirect user after entering wrong password?
  20. Increase of failed login attempts, brute force attacks? [closed]
  21. Login page ERROR: Cookies are blocked due to unexpected output
  22. Separate registration and login for different roles
  23. SSO / authentication integration with external ‘directory service’
  24. Preventing session timeout
  25. How reduce wordpress login session timeout time?
  26. How to prefill WordPress registration with social details
  27. Check for correct username on custom login form
  28. Disallow user from editing their own profile information
  29. I can’t access my site via wp-admin
  30. ‘Password field is empty’ error when using autofill in Chrome
  31. Removing username from the ‘wordpress_logged_in’ cookie
  32. How to show ‘login error’ and ‘lost password’ on my template page?
  33. What is $interim_login?
  34. Custom login form
  35. How to prefill the username/password fields on the login page
  36. wp_signon returns user, but the user is not logged in
  37. Adding extra authentication field in login page
  38. Prevent wp_login_form() from redirecting to wp-admin when there are errors
  39. Redirect user using the ‘wp_login_failed’ action hook if the error is ’empty_username’ or ’empty_password’
  40. wp_signon() does not authenticate user guidance needed
  41. What exactly is ReAuth?
  42. What are the differences between wp_users and wp_usermeta tables?
  43. Login members using web services
  44. Make my wordpress blog remember my login “forever”
  45. How to check in timber if user is loggedin?
  46. How do I change the language of only the login page?
  47. Disable WordPress 3.6 idle logout / login modal window / session expiration
  48. Stop WordPress from logging me out (need to keep me logged in)
  49. Woocommerce registration page [closed]
  50. How to disable autocomplete on the wp-login.php page
  51. Share login data/cookies between multiple installations
  52. Synchronize WordPress user accounts across multiple domains and installations without using WordPress MU
  53. How to pass users back and forth using session data?
  54. How do I change the logo on the login page?
  55. Why does WordPress hide the reset password key from the URL?
  56. Is it possible to sign in with user_email in WordPress?
  57. How to use current_user_can()?
  58. Avoid to load default WP styles in login screen
  59. WordPress registration message
  60. How to fake a WordPress login?
  61. how to display the wordpress login and register forms on a page?
  62. Does wp_logout_url() destroy a session? (Logging out question)
  63. How can I send a welcome email to a user AFTER they login for the first time?
  64. Can not login with correct username and password
  65. How to allow users login to WP from external domain and make REST requests
  66. Website Visible only to Registered users
  67. How can i increase the login expiration length?
  68. How do I use add_action from a class method?
  69. How to remove the WordPress logo from login and register page?
  70. How can I add a custom script to footer of login page?
  71. Brute force attack?
  72. Customize wp_new_user_notification_email()
  73. Need to execute a cron job
  74. Login email after registration never sent or received
  75. How can I create a separate blog that is private?
  76. How to keep always logged in development environment
  77. Add Confirm Password field in wp-login.php Password Reset page
  78. How do I use the WP REST API plugin and the OAuth Server plugin to allow for registration and login?
  79. Integrate recaptcha and wp_signon – what is needed?
  80. Stop users from logging in from multiple locations
  81. I want to disable E-Mail verifcation / activation when a user signs up for my WordPress site
  82. custom login page redirect to logged in user profile page
  83. Email address or username used to login in wordpress
  84. How do I check if a post is private?
  85. Front-end login: Redirect user to the post they had created
  86. Receiving “This content cannot be displayed in a frame” error on login page
  87. My login form does not work
  88. Programmatically log in a wordpress user
  89. Action wp_login_failed not working if only one field is filled out
  90. Getting “Cookies are blocked or not supported by your browser” on login page
  91. What is the purpose of logging out after WordPress upgrade?
  92. Is it alright for two people to simultaneously be logged into a WP site as administrator?
  93. wp-login.php redirecting to HTTPS
  94. Display last login time
  95. How to customise wp-login.php only for users who are setting a password for the first time?
  96. Intentionally Force Failed Login WordPress
  97. How do I turn off the ability to login?
  98. Gaining Login Access via the Database
  99. How can I test the login for an expired session?
  100. Give visitor access to password protected page/post via external script
Categories login Tags api, google, login, oauth
Passing form data on submit
How do I hide submenus from the top menu bar?

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Post Navigation Elementor
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • WPFacet multiple loop displaying duplicate content
  • Get the name of the template/*html file used
  • Fix: WordPress.DB.PreparedSQL.NotPrepared Plugin Check (PCP)
  • Removing unnecessary CSS and JS code from wp_head()
  • hexagonal image gallery. Am I on the right track? [closed]
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress