Catch and redirect 404 errors in WordPress with custom code

Log 404 errors and redirect old URLs without a plugin

Every 404 is a visitor who did not find what they were looking for: an old link from another site, a changed slug, a typo in a URL that was printed in a flyer. Knowing which URLs return 404 shows which redirects are worth adding. For a small site, a few lines on template_redirect can log the 404s and redirect the known old addresses, without a redirect plugin.

Problem: After a redesign some old URLs return 404, and nobody knows which ones visitors and search engines still request.

Solution: On template_redirect, when is_404() is true, first check a list of known old paths and redirect them with a 301; otherwise count the requested path in a non-autoloaded option, and show the most frequent ones to administrators.

Redirects and logging

<?php
add_action( 'template_redirect', 'ha_handle_404' );

function ha_handle_404() {
    if ( ! is_404() ) {
        return;
    }

    $path = wp_parse_url( isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '/', PHP_URL_PATH );
    $path = '/' . trim( (string) $path, '/' ) . '/';

    // Known old addresses: old path => new path
    $redirects = array(
        '/services/web-design/' => '/services/',
        '/old-contact/'         => '/contact/',
    );

    if ( isset( $redirects[ $path ] ) ) {
        wp_safe_redirect( home_url( $redirects[ $path ] ), 301 );
        exit;
    }

    // Count the 404, ignore obvious bot noise
    if ( preg_match( '~\.(php|env|git|sql|bak)~i', $path ) ) {
        return;
    }

    $log          = get_option( 'ha_404_log', array() );
    $log[ $path ] = isset( $log[ $path ] ) ? $log[ $path ] + 1 : 1;

    arsort( $log );
    update_option( 'ha_404_log', array_slice( $log, 0, 200, true ), false ); // top 200, not autoloaded
}

The redirect runs only for requests that are a 404 anyway, so it never interferes with existing pages. WordPress already handles changed post slugs by itself: when a post’s slug is edited, the old one is stored in _wp_old_slug and redirected automatically, so the list above is for pages that were removed or restructured.

Showing the log

<?php
add_action( 'admin_menu', function () {
    add_management_page( '404 log', '404 log', 'manage_options', 'ha-404-log', function () {
        echo '<div class="wrap"><h1>404 log</h1><table class="widefat striped"><tbody>';
        foreach ( (array) get_option( 'ha_404_log', array() ) as $path => $count ) {
            printf( '<tr><td>%s</td><td>%d</td></tr>', esc_html( $path ), (int) $count );
        }
        echo '</tbody></table></div>';
    } );
} );

The page appears under Tools. The paths with the highest counts are the redirects to add first. Google Search Console shows the 404s that Google found, including the pages that link to them.

Choosing the target

Redirect to the page that replaced the old one, not to the home page: a redirect of everything to the home page is treated by Google as a “soft 404” and passes no value. If there is no replacement, a 404 (or 410 for content removed on purpose) is the honest answer.

NOTE: A 301 is cached by browsers for a long time, so test new rules with a 302 first and switch to 301 when they are right. And avoid chains: if A already redirects to B and B moves to C, change A to point to C directly.