You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

wp_login_form登录后无法保留当前页面的问题求助

解决WordPress登录后跳转当前页面的问题

Absolutely, this is totally achievable! I’ve run into this exact issue before—sometimes relying on $_SERVER variables can be finicky depending on your server setup or how the modal is loaded. Let’s walk through fixes and alternative ways to grab the current page URL that play nicer with WordPress.

首先:优化你的现有redirect写法(最推荐)

Your original code manually builds the URL, but WordPress has built-in functions that handle HTTPS, permalinks, and server quirks automatically. Replace your redirect line with either:

If you’re adding the login form directly to a post/page template or a part tied to a specific post, this is perfect:

'redirect' => get_permalink()

Option 2: Use home_url() with the current request

For header templates or areas not tied to a single post, this will reliably get the full current URL:

'redirect' => home_url( $_SERVER['REQUEST_URI'] )

This replaces your manual is_ssl() check because home_url() automatically uses the correct protocol (HTTP/HTTPS) based on your site settings.

Alternative Method 1: Pass the current URL via a hidden field

If your modal loads dynamically (like via AJAX), sometimes the URL captured when the page first loads isn’t the same as what the user sees when they click login. To fix this, add a hidden field to your login form that explicitly tells WordPress where to redirect:

Add this to your $args array:

'form_extra' => '<input type="hidden" name="redirect_to" value="' . esc_url( get_permalink() ) . '">'

WordPress prioritizes the redirect_to POST parameter over the redirect argument in wp_login_form(), so this guarantees the user lands back on the current page.

Alternative Method 2: Use the global $wp object

For sites with custom permalinks, this method leverages WordPress’s internal rewrite system to get the exact request path:

global $wp;
'redirect' => esc_url( home_url( add_query_arg( array(), $wp->request ) ) )

This is great if you have complex URL structures—$wp->request gives you the clean, rewritten path without messy query strings.

Why your original code might be failing

Your manual URL build works in most cases, but some servers or caching plugins can alter $_SERVER['REQUEST_URI'], or if your modal loads after the initial page render, the value might not reflect the current page. Using WordPress’s native functions avoids these edge cases.

One last note: Always wrap your URLs with esc_url() to prevent XSS vulnerabilities—better safe than sorry!

内容的提问来源于stack exchange,提问作者Erik Berge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:49:13