wordpresswordpress-theming

WordPress Site Kit: Add Sign in with Google button in theme header without redirecting to login page


I'm using the Site Kit by Google plugin on my WordPress website and have enabled the Sign in with Google feature. Now, I want to add a Sign in with Google button in my theme’s header that directly opens the Google authentication popup (one-click sign-in) instead of redirecting users to the default WordPress login page.

What I’ve Tried So Far:

  1. I added a button in header.php and tried using wp_login_url(), but it redirects users to the WordPress login screen instead of opening the Google authentication popup.
  2. I attempted to use the Google Identity Services API with this shortcode in functions.php:
function google_signin_button_shortcode() {
    ob_start();
    ?>
    <?php if (!is_user_logged_in()) : ?>
        <div id="g_id_onload"
            data-client_id="YOUR_GOOGLE_CLIENT_ID"
            data-context="signin"
            data-ux_mode="popup"
            data-callback="handleCredentialResponse">
        </div>

        <div id="g_id_signin"
            class="g_id_signin"
            data-type="standard">
        </div>

        <script>
            function handleCredentialResponse(response) {
                console.log("Google ID Token: " + response.credential);
                window.location.reload();
            }
        </script>

        <script src="https://accounts.google.com/gsi/client" async defer></script>

    <?php else : ?>
        <a href="<?php echo esc_url( wp_logout_url( home_url() ) ); ?>" class="google-logout-button">
            Logout
        </a>
    <?php endif; ?>
    <?php
    return ob_get_clean();
}
add_shortcode('google_signin', 'google_signin_button_shortcode');

This added the button but not working properly.

Is there any function provided by google site kit plugin (I am unable to find in the documentation) to add a button, or is there a better way of doing it?


Solution

  • There is an open GitHub issue in relation to adding Sign in with Google via a shortcode, which would make your objective easier. Chime in on the below GitHub issue and subscribe for updates:
    https://github.com/google/site-kit-wp/issues/10150

    There may also be plugins that allow you to insert blocks into shortcodes or into WordPress hooks. Here's one such example: https://wordpress.org/plugins/blocks-to-shortcode/