Last active
February 14, 2023 12:59
-
-
Save marklchaves/86f23654c0f4eb7de2223c85e1da31ec to your computer and use it in GitHub Desktop.
Custom Login Redirect: Use built-in WordPress hooks to redirect people to your custom login page when wp-login.php gets called
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php // Ignore this first line when copying to your child theme's functions.php file. | |
/** | |
* Redirects wp-login.php to your custom login page. | |
*/ | |
function redirect_login_page() { | |
$login_page = home_url( '/my-custom-login-page/' ); | |
$page_viewed = basename($_SERVER['REQUEST_URI']); | |
if( $page_viewed == "wp-login.php" && $_SERVER['REQUEST_METHOD'] == 'GET' ) { | |
wp_redirect( $login_page ); | |
exit; | |
} | |
} | |
add_action( 'init','redirect_login_page' ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php // Ignore this first line when copying to your child theme's functions.php file. | |
/** | |
* Filters the login URL. | |
* | |
* Example adapted from https://developer.wordpress.org/reference/hooks/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 string | |
*/ | |
function wordpress_custom_login_url( $login_url, $redirect, $force_reauth ) { | |
// This will append your custom login page's path to you main site URL (e.g. https://domain.com/custom-login/) | |
$login_url = site_url( '/my-custom-login-page/', 'login' ); // Change to your path. | |
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 ); | |
} | |
return $login_url; | |
} | |
add_filter( 'login_url', 'wordpress_custom_login_url', 10, 3 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment