vapvarun icon

Redirect wp-login.php to a custom login page, but allow exceptions for SSO/2FA

vapvarun | PRO | 09/30/24 08:07:55 AM UTC (Edited) | 0 ⭐ | 514 👁️ | Never ⏰ | []
PHP |

1.53 KB

|

Software

|

0 👍

/

0 👎

// Redirect wp-login.php to a custom login page, but allow exceptions for SSO/2FA.
add_action('init', 'custom_force_custom_login_page');
 
function custom_force_custom_login_page() {
    // Define the custom login page URL
    $custom_login_page = home_url('/login/'); // Replace '/custom-login/' with your custom login page URL.
 
    // Get the current request
    $current_page = basename($_SERVER['REQUEST_URI']);
 
    // If the current page is wp-login.php, and not performing login-related actions, redirect
    if ($current_page === 'wp-login.php' && !is_user_logged_in()) {
 
        // List of actions that should not trigger the redirect (SSO, 2FA, etc.)
        $allowed_actions = ['logout', 'lostpassword', 'resetpass', 'rp', 'login']; // Add any other actions as needed
 
        // Check if any of the allowed actions are being performed
        $is_allowed_action = false;
        if (isset($_GET['action']) && in_array($_GET['action'], $allowed_actions)) {
            $is_allowed_action = true;
        }
 
        // Allow SSO plugins and 2FA plugins by checking the presence of specific query strings or parameters
        // Modify the conditions based on the specific plugins you use.
        if (isset($_GET['sso']) || isset($_GET['2fa'])) {
            $is_allowed_action = true;
        }
 
        // If not performing allowed actions or plugin-related requests, redirect to the custom login page
        if (!$is_allowed_action) {
            wp_redirect($custom_login_page);
            exit();
        }
    }
}
 

Comments