Subtle diagonal pinstripe pattern in light grey and cream, giving an impression of printed editorial paper

Custom WordPress login pages, redirects and errors

WordPress ships with a dependable sign-in screen, but many businesses want their branding, wording and post-login destination without replacing the authentication layer. Creating a custom login page in WordPress with redirects and error handling means controlling the interface while leaving cookies, sessions, nonces and user records under WordPress control.

A Melbourne WooCommerce retailer may want customers to sign in without seeing the generic wp-login.php screen, then return to an order or checkout. A Sydney agency may need staff to reach wp-admin while editors reach a custom dashboard. Australian teams often use “sign in” for the action and “sign-in page” for the screen, so labels should follow that familiar wording.

The safest design separates three jobs: authenticating the person, deciding where they may go, and explaining failures. A theme template offers visual freedom but disappears when the theme changes; a small plugin or shortcode survives theme updates and can be enabled on one selected page. The default wp-login.php route should remain available for password resets and recovery links.

Plan the page as a public entry point rather than a private WordPress screen. Confirm HTTPS, test every intended destination, and decide what data may appear in logs. For many organisations subject to the Privacy Act 1988 and Australian Privacy Principles, data minimisation is especially important, so passwords, reset links and raw form submissions should never be recorded.

Choose the right implementation

Choose the smallest layer that meets the requirement. A dedicated child-theme template works for a tightly controlled design, while a shortcode-based plugin is easier to distribute to client sites whose themes vary. Authentication plugins can add MFA or social login, but they do not remove the need to validate redirect targets and present errors consistently.

For a public login page, give it a predictable slug such as /sign-in/ and keep the shortcode on that page only. Where a theme or plugin lets you change the sitewide login URL, point that setting at the branded route. Avoid catching every request to wp-login.php: core already handles important edge cases, including password resets, account activation and application-password challenges. Redirect those workflows back to the branded route rather than replacing them.

Many Australian small businesses run WordPress on cPanel or managed hosting with selectable PHP 8.2 or 8.3 releases. Check the extension list, memory limit and mail configuration on staging before deployment. On shared hosting, PHP workers are limited, so authentication work should remain a normal POST rather than an expensive script that loops or retries.

Create the login form and handler

Create a plugin with a shortcode, then process its POST data through template_redirect before WordPress sends any HTML. This timing allows wp_signon() to establish the authentication cookie and wp_safe_redirect() to work without headers having already been sent. The password must be unslashed but never shortened or transformed; wp_signon() should receive it intact.

add_action( 'template_redirect', 'site_login_handle_submission' );
add_shortcode( 'site_login', 'site_login_render' );

function site_login_post_value( $key ) {
    if ( ! isset( $_POST[ $key ] ) || ! is_string( $_POST[ $key ] ) ) {
        return '';
    }

    return wp_unslash( $_POST[ $key ] );
}

function site_login_handle_submission() {
    if ( 'POST' !== ( $_SERVER['REQUEST_METHOD'] ?? '' ) || ! is_singular() ) {
        return;
    }

    $page = get_queried_object();
    if ( ! $page || ! has_shortcode( $page->post_content, 'site_login' ) ) {
        return;
    }

    $GLOBALS['site_login_error']    = '';
    $GLOBALS['site_login_username'] = '';

    $nonce    = site_login_post_value( 'login_nonce' );
    $username = sanitize_text_field( site_login_post_value( 'log' ) );
    $password = site_login_post_value( 'pwd' );
    $redirect_to = '';

    if ( isset( $_REQUEST['redirect_to'] ) && is_string( $_REQUEST['redirect_to'] ) ) {
        $redirect_to = esc_url_raw( wp_unslash( $_REQUEST['redirect_to'] ) );
    }

    if ( ! wp_verify_nonce( $nonce, 'site_login' ) ) {
        $GLOBALS['site_login_error'] = 'This form has expired. Reload the page and try again.';
    } elseif ( '' === $username || '' === $password ) {
        $GLOBALS['site_login_error'] = 'Enter both your username and password.';
    } else {
        $user = wp_signon(
            array(
                'user_login'    => $username,
                'user_password' => $password,
                'remember'      => isset( $_POST['rememberme'] ) && 'forever' === $_POST['rememberme'],
            ),
            is_ssl()
        );

        if ( is_wp_error( $user ) ) {
            $codes   = $user->get_error_codes();
            $generic = array_intersect(
                array( 'invalid_username', 'invalid_email', 'incorrect_password' ),
                $codes
            );

            $GLOBALS['site_login_error'] = $generic
                ? 'The username or password is not correct.'
                : $user->get_error_message();
        } else {
            $destination = wp_validate_redirect( $redirect_to, '' );
            $admin_path  = (string) wp_parse_url( admin_url(), PHP_URL_PATH );
            $target_path = (string) wp_parse_url( $destination, PHP_URL_PATH );
            $wants_admin = $destination && $admin_path && 0 === strpos( $target_path, $admin_path );
            $can_admin   = user_can( $user->ID, 'edit_posts' );

            if ( $wants_admin && ! $can_admin ) {
                $destination = '';
            }

            if ( ! $destination ) {
                $destination = $can_admin
                    ? admin_url()
                    : home_url( '/my-account/' );
            }

            wp_safe_redirect( $destination, 302, 'Site login' );
            exit;
        }
    }

    $GLOBALS['site_login_username'] = $username;
}

function site_login_render() {
    $error       = $GLOBALS['site_login_error'] ?? '';
    $username    = $GLOBALS['site_login_username'] ?? '';
    $redirect_to = '';
    $fallback    = home_url( '/my-account/' );
    $form_action = get_permalink();

    if ( isset( $_REQUEST['redirect_to'] ) && is_string( $_REQUEST['redirect_to'] ) ) {
        $redirect_to = esc_url_raw( wp_unslash( $_REQUEST['redirect_to'] ) );
    }
    ?>
<form method="post" action="<?php echo esc_url( $form_action ); ?>">
    <?php if ( $error ) : ?>
        <p class="site-login-error" role="alert">
            <?php echo esc_html( $error ); ?>
        </p>
    <?php endif; ?>

    <label for="site-login-user">Username or email</label>
    <input
        id="site-login-user"
        name="log"
        type="text"
        value="<?php echo esc_attr( $username ); ?>"
        autocomplete="username"
        required
    >

    <label for="site-login-password">Password</label>
    <input
        id="site-login-password"
        name="pwd"
        type="password"
        autocomplete="current-password"
        required
    >

    <label>
        <input name="rememberme" type="checkbox" value="forever">
        Remember me
    </label>

    <input
        type="hidden"
        name="redirect_to"
        value="<?php echo esc_attr( $redirect_to ? $redirect_to : $fallback ); ?>"
    >

    <?php wp_nonce_field( 'site_login', 'login_nonce' ); ?>

    <button type="submit">Sign in</button>
</form>

Install the plugin, add [site_login] to a dedicated page, and place its styles in the child theme rather than embedding a large CSS block in the template. The example retains the username after a failure but never repopulates the password. Change /my-account/ to the actual customer-account endpoint used by the site.

Give the error region role="alert", associate helper text with inputs, keep the submit button reachable by keyboard, and preserve visible focus styles. Test at 200 percent zoom and on a narrow phone viewport. Do not make JavaScript mandatory: a conventional POST still works when scripts fail, which matters on regional mobile connections and older devices used by some warehouse and retail staff.

Control post-login destinations

Treat redirect_to as untrusted input even when it appears in a hidden field. wp_validate_redirect() rejects disallowed cross-site targets, and wp_safe_redirect() performs the final host check immediately before sending the Location header. The fallback should match the user’s role rather than sending every customer to wp-admin, where a permission message would be confusing.

Use one source of truth for destinations. Users with edit_posts can go to admin_url(), while subscribers can go to /my-account/; WooCommerce customers can return to checkout with the cart intact and Australian-dollar totals unchanged. If the requested URL is missing or invalid, derive the fallback from the authenticated user. A small role-to-destination map is easier to maintain than scattered conditional checks.

Build links to the custom page with a relative destination, such as /sign-in/?redirect_to=/my-account/. Retain the original target when an expired session returns to sign-in, but cap its length and decode it once. Test account, checkout, password-reset and logout journeys. Redirect loops usually come from sending a protected page back to sign-in without preserving where the visitor intended to go.

Display useful and safe errors

Classify failures before displaying them. A missing field is a form validation problem, an expired nonce is a stale-session problem, invalid credentials are an authentication problem, and a plugin or server failure is an operational problem. Keep the visitor-facing copy specific enough to help without revealing whether an account exists; the generic credential message in the example prevents that distinction.

Live form feedback can follow the same progressive-enhancement discipline described for custom AJAX search, but sign-in is security-sensitive. Keep the normal POST as the source of truth, submit to the same origin, and use an aria-live region for client-side validation. Do not send credentials to a third-party script or turn a failed login into a JSON-only experience that visitors without JavaScript cannot use.

Operational logs should record a timestamp, a coarse event type and an anonymised or truncated identifier, never a password or full reset URL. Store events in UTC and render them with wp_date() in the site’s configured zone. That distinction prevents confusion when support teams in Sydney and Melbourne observe daylight-saving changes while Brisbane and Perth do not shift on the same date.

Practical hardening and maintenance for Australian teams

Rate limiting belongs in front of authentication, not in the visual template. Use a reputable attempts-limit or security plugin, enforce unique administrator accounts and MFA, and rotate application passwords. Keep WordPress, PHP and the server current, restrict wp-admin by role, and configure HTTPS, HSTS and secure cookies at the host. The custom page should not create its own password database or maintain a parallel session.

Developers working in Emacs can pair it with a formatter using Magik Code formatting, then run syntax checks on the plugin before review. Keep the handler and form markup in separate files when the business rules grow, and cover role selection, invalid destinations, nonce expiry and authentication failures with repeatable tests.

Run the final test with a real customer account, an editor account and an administrator account on staging. Confirm the sign-in page in mobile Safari and Chrome, verify that WooCommerce carts survive the round trip, and watch the hosting logs for PHP warnings. Once deployed, the page can be restyled without touching WordPress authentication, while redirects and failure messages remain controlled by the plugin.