WP_LOGIN_Form()重定向同一页

时间:2021-08-07 作者:chamboy

我正在尝试使用wp\\u login\\u form()重定向同一页面。这是我的密码

function loginform() {
if ( is_user_logged_in()){
echo \'<p> <a  href="\'.esc_url(home_url(\'/my-dashboard/\')).\'" >\'.esc_html( __( \'Thank you.! Please Go to dashboard\', \'mytheme\' )).\'</a></p>\';}
else{
$args = array(\'redirect\' => home_url(), \'id_username\' => \'user\',\'id_password\' => \'pass\',);
wp_login_form( $args );}}
add_shortcode(\'login-form\', \'loginform\'); 
我更改了默认的wp登录。使用此筛选器的php url

add_filter( \'login_url\', \'new_login_page\', 10, 3 );
function new_login_page( $login_url, $redirect, $force_reauth ) {$login_page = esc_url(home_url( \'/login/\'));return add_query_arg( \'redirect_to\', $redirect, $login_page );}
然后调用未登录的用户,通过将此代码添加到

echo \'<a href="\'. esc_url(wp_login_url( get_permalink())) .\'"><span class="icon" ></span>\'.esc_html( __( \'login\', \'mytheme\' )).\'</a> \'; 
一切正常,但登录后不会重定向到上一页。。有什么帮助吗?非常感谢。。谢谢:)

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

after logged in it wont redirect to previous page

It\'s because in your loginform() function, the \'redirect\' => home_url() below sets the redirect URL to the homepage URL:

$args = array(\'redirect\' => home_url(), \'id_username\' => \'user\',\'id_password\' => \'pass\',);

So if you want to redirect to the previous page, then remove the redirect argument above, or use the code below, which means if redirect_to=<URL> is present in the current URL as in example.com/login/?redirect_to=https://example.com/some-page/, then the specified URL will be used instead:

// Define your $args like this:
$args = array( \'id_username\' => \'user\', \'id_password\' => \'pass\' );

// Then add the \'redirect\', if the URL has the redirect_to=<URL>.
if ( ! empty( $_REQUEST[\'redirect_to\'] ) ) {
    $args[\'redirect\'] = $_REQUEST[\'redirect_to\'];
}

See the wp_login_form() documentation for more details on the redirect and other arguments.

Additional Notes

Excerpt from codex.wordpress.org/Shortcode_API:

The return value of a shortcode handler function is inserted into thepost content output in place of the shortcode macro. Remember to use return and not echo - anything that is echoed will be output to the browser, but it won\'t appear in the correct place on the page.

Therefore your loginform() should actually return the output and not echoing it (or anything else), because in addition to the above issue (shortcode appearing in the wrong place), an echo in the function would result in a failure in saving a post via the block editor (Gutenberg) which uses the REST API (so if your function echo something, the REST API response will be invalid).

So in that function, change the echo \'<p> to return \'<p>, then in the $args array, add \'echo\' => false, and finally change the wp_login_form( $args ) to return wp_login_form( $args ).