WordPress PHP Free

WordPress: Log 404 Errors to Find Broken Links

Log every 404 on your WordPress site so you can see which broken links visitors actually hit — and fix them.

23 lines · Updated Nov 26, 2026

Preview of WordPress: Log 404 Errors to Find Broken Links
wordpress-log-404-errors.php
<?php

// Add to your theme's functions.php or a code-snippets plugin.
add_action('template_redirect', 'log_404_errors');

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

    $url = home_url(add_query_arg(null, null));
    $referrer = wp_get_referer() ? wp_get_referer() : 'direct';

    error_log(sprintf(
        '[404] %s | from: %s',
        $url,
        $referrer
    ));
}

// View the log in wp-content/debug.log (with WP_DEBUG_LOG on),
// or in your hosting error log. Then add a redirect for the
// URLs that get hit most often.

About this snippet

Every 404 error is a visitor who wanted something and did not find it — often because of an old link, a changed slug or a typo in a menu. Search Console shows some of them days later; this snippet logs them as they happen. It records each 404 with the requested URL, the referring page and the time, so you can fix broken links and add redirects where they matter.

How it works

  1. The snippet runs on a WordPress hook that fires on every front-end request.
  2. When WordPress has decided the request is a 404, it records the requested URL, the referrer and the date.
  3. Entries are written to a log so you can review them later.

How to use the log

  • Referrer is your own site: you have a broken internal link — fix the link.
  • Referrer is another site or Google: the page used to exist — add a 301 redirect to the closest matching page.
  • Random paths like /wp-admin.php.bak or /.env: bots scanning for weaknesses — ignore them, but make sure those files really do not exist.

Keep it under control

  • Limit the log size or rotate it, so bot traffic cannot fill your disk.
  • Store the log outside public folders, or protect it, because it contains visitor data such as referrers.
  • Review it weekly, fix the top items, then clear it.

Common problems

  • Nothing logged: a caching layer or CDN may serve 404 pages without running WordPress, or your theme handles missing pages with a 200 status (a "soft 404") — check the real status code in DevTools.

FAQ

Do 404 errors hurt SEO? 404s for pages that never existed are normal. Broken internal links and lost backlinks to removed pages are worth fixing with redirects.

Related: Dynamic sitemap · Custom dashboard widget

How to install

Add the code to your theme's functions.php or a code-snippets plugin. Turn on WP_DEBUG_LOG in wp-config.php to write to wp-content/debug.log, then check it weekly.

Share this snippet

See all
Chat with us