Using WordPress ‘pre_handle_404’ PHP filter

pre_handle_404 is a WordPress PHP filter that allows you to control the default header status handling for 404 errors, enabling you to short-circuit the process and return early if desired.

Usage

add_filter('pre_handle_404', 'your_custom_function', 10, 2);

function your_custom_function($preempt, $wp_query) {
  // your custom code here
  return $preempt;
}

Parameters

  • $preempt (bool) – Determines whether to short-circuit default header status handling. Default is false.
  • $wp_query (WP_Query) – The WordPress Query object.

More information

See WordPress Developer Resources: https://developer.wordpress.org/reference/hooks/pre_handle_404/

Examples

Redirect to custom 404 page

Redirect users to a custom 404 page instead of the default one provided by the theme.

add_filter('pre_handle_404', 'redirect_custom_404_page', 10, 2);

function redirect_custom_404_page($preempt, $wp_query) {
  if (is_404()) {
    wp_redirect('/custom-404-page/');
    exit;
  }
  return $preempt;
}

Log 404 errors

Log 404 errors with the requested URL and timestamp for further analysis.

add_filter('pre_handle_404', 'log_404_errors', 10, 2);

function log_404_errors($preempt, $wp_query) {
  if (is_404()) {
    $log_file = '404_errors.log';
    $message = date("Y-m-d H:i:s") . " - " . $_SERVER['REQUEST_URI'] . "\n";
    error_log($message, 3, $log_file);
  }
  return $preempt;
}

Show maintenance page on 404

Display a maintenance page to users if a 404 error occurs.

add_filter('pre_handle_404', 'show_maintenance_page_on_404', 10, 2);

function show_maintenance_page_on_404($preempt, $wp_query) {
  if (is_404()) {
    include 'maintenance-page.php';
    exit;
  }
  return $preempt;
}

Restrict 404 handling for specific post types

Disable 404 handling for a specific custom post type, letting WordPress handle it as a normal request.

add_filter('pre_handle_404', 'disable_404_for_custom_post_type', 10, 2);

function disable_404_for_custom_post_type($preempt, $wp_query) {
  if ($wp_query->is_single() && 'custom_post_type' == $wp_query->get('post_type')) {
    return true;
  }
  return $preempt;
}

Send email notifications for 404 errors

Send an email notification to the administrator when a 404 error occurs.

add_filter('pre_handle_404', 'send_email_on_404', 10, 2);

function send_email_on_404($preempt, $wp_query) {
  if (is_404()) {
    $admin_email = get_option('admin_email');
    $subject = '404 Error on Your Website';
    $message = 'A 404 error occurred on the following URL: ' . $_SERVER['REQUEST_URI'];
    wp_mail($admin_email, $subject, $message);
  }
  return $preempt;
}