函数文档

wp_login_url()

💡 云策文档标注

概述

wp_login_url() 函数用于生成 WordPress 登录页面的 URL,支持通过参数设置登录后的重定向路径和强制重新授权选项。该函数返回未 HTML 编码的字符串,并可通过 'login_url' 过滤器进行自定义。

关键要点

  • 函数返回登录 URL,基于 site_url('wp-login.php', 'login') 构建。
  • 参数 $redirect 用于指定登录后重定向的绝对路径,建议使用 site_url() 生成。
  • 参数 $force_reauth 为布尔值,默认为 false,设置为 true 可强制重新授权。
  • 函数内部使用 add_query_arg() 添加查询参数,并通过 apply_filters() 应用 'login_url' 过滤器。
  • 返回的 URL 未 HTML 编码,使用时需注意安全性。

代码示例

// 基本用法:生成登录 URL
$login_url = wp_login_url();

// 带重定向的用法:登录后跳转到指定页面
$redirect_url = site_url('/mypage/');
$login_url = wp_login_url($redirect_url);

// 强制重新授权的用法
$login_url = wp_login_url('', true);

注意事项

  • $redirect 参数必须是绝对 URL,例如 http://example.com/mypage/,推荐使用 site_url() 函数生成。
  • 在 404 页面或私有内容场景下,使用 get_permalink() 可能返回 false,应考虑使用当前请求 URL 作为重定向目标。
  • 函数自 WordPress 2.7.0 版本引入,'login_url' 过滤器在 4.2.0 版本增加了 $force_reauth 参数。

📄 原文内容

Retrieves the login URL.

Parameters

$redirectstringrequired
Path to redirect to on log in.
$force_reauthbooloptional
Whether to force reauthorization, even if a cookie is present.

Default:false

Return

string The login URL. Not HTML-encoded.

More Information

$redirect argument must be absolute, such as http://example.com/mypage/. For best results, use site_url( ‘/mypage/ ‘ ).

Source

function wp_login_url( $redirect = '', $force_reauth = false ) {
	$login_url = site_url( 'wp-login.php', 'login' );

	if ( ! empty( $redirect ) ) {
		$login_url = add_query_arg( 'redirect_to', urlencode( $redirect ), $login_url );
	}

	if ( $force_reauth ) {
		$login_url = add_query_arg( 'reauth', '1', $login_url );
	}

	/**
	 * Filters the login URL.
	 *
	 * @since 2.8.0
	 * @since 4.2.0 The `$force_reauth` parameter was added.
	 *
	 * @param string $login_url    The login URL. Not HTML-encoded.
	 * @param string $redirect     The path to redirect to on login, if supplied.
	 * @param bool   $force_reauth Whether to force reauthorization, even if a cookie is present.
	 */
	return apply_filters( 'login_url', $login_url, $redirect, $force_reauth );
}

Hooks

apply_filters( ‘login_url’, string $login_url, string $redirect, bool $force_reauth )

Filters the login URL.

Changelog

Version Description
2.7.0 Introduced.

User Contributed Notes

  1. Skip to note 7 content


    Anonymous User



    For the redirect example to the current URL via get_permalink() above, note that if the request is a 404, get_permalink() will return false, so you may want to grab the actual URL instead.

    A scenario where it could be useful to still redirect to your current URL even if it was a 404, would be if the current URL was a private post, and your user was not yet logged-in – hence ended up on a 404.

    In that case, if you show them a login link, they should be redirected back to the current URL (i.e. the private post), so that they finally can access it.

    request ) ); ?>
    <a href="<?php echo esc_url( wp_login_url( $current_url )  ); ?>"></a>