如何在WordPress主题头部添加Site Kit谷歌弹窗登录按钮?
利用Site Kit by Google实现弹窗式谷歌登录按钮
核心结论
Site Kit by Google本身已经集成了Google Identity Services(GSI)的登录逻辑,无需单独编写完整的GSI初始化代码,你可以直接复用插件已加载的资源和配置,避免冲突并简化实现。
你之前代码的问题
你手动引入GSI客户端脚本,会和Site Kit已加载的脚本产生冲突;同时你的回调函数仅打印token并刷新页面,没有将token传递给WordPress完成身份验证流程,所以无法实现登录。
最优实现方案
以下是基于Site Kit内置能力的实现方式,直接在主题中调用即可:
方法1:短代码实现(推荐)
将以下代码添加到主题的functions.php中:
function sk_google_signin_button_shortcode() { if (is_user_logged_in()) { return '<a href="' . esc_url(wp_logout_url(home_url())) . '" class="google-logout-button">退出登录</a>'; } // 获取Site Kit配置的谷歌客户端ID $credentials = get_option('googlesitekit_credentials'); $client_id = $credentials['oauth_client_id'] ?? ''; if (empty($client_id)) { return '<p>请先在Site Kit中完成谷歌账号配置</p>'; } ob_start(); ?> <div id="g_id_onload" data-client_id="<?php echo esc_attr($client_id); ?>" data-context="signin" data-ux_mode="popup" data-callback="skHandleGoogleSignIn"> </div> <div class="g_id_signin" data-type="standard" data-shape="rectangular" data-theme="outline" data-text="signin_with"> </div> <script> function skHandleGoogleSignIn(response) { // 发送token到WordPress进行验证 fetch('<?php echo admin_url('admin-ajax.php'); ?>', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-WP-Nonce': '<?php echo wp_create_nonce('sk-google-signin'); ?>' }, body: 'action=sk_google_signin&token=' + encodeURIComponent(response.credential) }) .then(res => res.json()) .then(data => { if (data.success) { // 登录成功后刷新页面或跳转 window.location.href = '<?php echo esc_url(home_url()); ?>'; } else { alert('登录失败:' + data.message); } }) .catch(err => console.error('登录请求失败:', err)); } </script> <?php return ob_get_clean(); } add_shortcode('sk_google_signin', 'sk_google_signin_button_shortcode'); // 处理AJAX登录请求 function sk_handle_google_signin_ajax() { check_ajax_referer('sk-google-signin'); if (!isset($_POST['token'])) { wp_send_json_error(['message' => '缺少认证token']); } // 调用Site Kit的登录验证逻辑 $user = apply_filters('googlesitekit_authenticate_user', null, $_POST['token']); if ($user instanceof WP_User) { wp_set_current_user($user->ID); wp_set_auth_cookie($user->ID); wp_send_json_success(); } else { wp_send_json_error(['message' => '身份验证失败']); } } add_action('wp_ajax_nopriv_sk_google_signin', 'sk_handle_google_signin_ajax'); add_action('wp_ajax_sk_google_signin', 'sk_handle_google_signin_ajax');
然后在主题的header.php中需要显示按钮的位置添加短代码:
<?php echo do_shortcode('[sk_google_signin]'); ?>
方法2:直接在header.php中嵌入代码
如果不想用短代码,也可以直接将以下代码插入到header.php的合适位置:
<?php if (is_user_logged_in()) : ?> <a href="<?php echo esc_url(wp_logout_url(home_url())); ?>" class="google-logout-button">退出登录</a> <?php else : ?> <?php $credentials = get_option('googlesitekit_credentials'); $client_id = $credentials['oauth_client_id'] ?? ''; if (!empty($client_id)) : ?> <div id="g_id_onload" data-client_id="<?php echo esc_attr($client_id); ?>" data-context="signin" data-ux_mode="popup" data-callback="skHandleGoogleSignIn"> </div> <div class="g_id_signin" data-type="standard" data-shape="rectangular" data-theme="outline" data-text="signin_with"> </div> <script> function skHandleGoogleSignIn(response) { fetch('<?php echo admin_url('admin-ajax.php'); ?>', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-WP-Nonce': '<?php echo wp_create_nonce('sk-google-signin'); ?>' }, body: 'action=sk_google_signin&token=' + encodeURIComponent(response.credential) }) .then(res => res.json()) .then(data => { if (data.success) { window.location.href = '<?php echo esc_url(home_url()); ?>'; } else { alert('登录失败:' + data.message); } }) .catch(err => console.error('登录请求失败:', err)); } </script> <?php else : ?> <p>请先在Site Kit中完成谷歌账号配置</p> <?php endif; ?> <?php endif; ?>
同时需要将上述的sk_handle_google_signin_ajax函数添加到functions.php中。
关键说明
- 无需手动引入GSI客户端脚本:Site Kit已经在前端加载了
https://accounts.google.com/gsi/client,重复引入会导致冲突。 - 利用Site Kit的
googlesitekit_authenticate_user过滤器:该过滤器已经封装了谷歌token的验证逻辑,无需自己编写JWT解析代码。 - 安全处理:使用
wp_create_nonce和check_ajax_referer防止CSRF攻击,所有输出都用esc_attr/esc_url进行转义。
内容的提问来源于stack exchange,提问作者Alok Jain
相关产品推荐
相关产品推荐

