Redirect Users to a Custom Page Upon Login or Logout in WordPress

Redirect Users to a Custom Page Upon Login or Logout in WordPress

Want to redirect users to a custom page after login or logout without using a plugin? This WordPress tutorial shows you how to do it the clean, code-friendly way! Whether you’re building a membership site, customizing user experience, or just want more control over navigation, this guide is your shortcut to smarter redirects.

Watch Video

Code Used:

// Start session safely
function start_session_early() {
    if (session_status() === PHP_SESSION_NONE && !headers_sent()) {
        session_start();
    }
}
add_action('init', 'start_session_early', 1);

// Save last visited page (excluding login, register, logout)
function save_last_visited_page() {
    if (!is_user_logged_in() && !is_admin()) {
        $excluded_pages = ['login', 'my-account', 'logout'];
        $current_url = $_SERVER['REQUEST_URI'];

        foreach ($excluded_pages as $slug) {
            if (strpos($current_url, $slug) !== false) {
                return;
            }
        }

        $_SESSION['last_visited_page'] = $current_url;
    }
}
add_action('template_redirect', 'save_last_visited_page');

// Redirect to last visited page after login
function redirect_after_login($redirect_to, $request, $user) {
    if (!is_wp_error($user) && !empty($_SESSION['last_visited_page'])) {
        $redirect_url = home_url($_SESSION['last_visited_page']);
        unset($_SESSION['last_visited_page']);
        return $redirect_url;
    }
    return home_url();
}
add_filter('login_redirect', 'redirect_after_login', 10, 3);

// Redirect after logout
function redirect_after_logout() {
    wp_redirect(home_url());
    exit;
}
add_action('wp_logout', 'redirect_after_logout');

// Redirect after registration
function redirect_after_registration($user_id) {
    wp_redirect(home_url('/my-account'));
    exit;
}
add_action('user_register', 'redirect_after_registration');