Using WordPress ‘is_404()’ PHP function

The is_404() WordPress PHP function determines whether the query has resulted in a 404 (returns no results).

Usage

if (is_404()) {
    // Execute code when a 404 error occurs
}

Parameters

  • None

More information

See WordPress Developer Resources: is_404()

Examples

Display a custom 404 error message

If the is_404() function returns true, display a custom error message.

if (is_404()) {
    echo '<p><strong>Oops!</strong> The page you were looking for could not be found.</p>';
}

Show a search form on 404 pages

Add a search form to help users find other content when they encounter a 404 error.

if (is_404()) {
    get_search_form();
}

Redirect 404 pages to the homepage

Automatically redirect users to the homepage when a 404 error occurs.

if (is_404()) {
    wp_redirect(home_url());
    exit;
}

Log 404 errors

Keep track of 404 errors by logging them in a custom log file.

if (is_404()) {
    $log_file = '404_log.txt';
    $current_url = home_url(add_query_arg(array()));
    file_put_contents($log_file, $current_url . PHP_EOL, FILE_APPEND);
}

Load a custom 404 template

Load a custom 404 template file when a 404 error occurs.

if (is_404()) {
    get_template_part('custom-404');
}