The graceful_fail_template WordPress PHP filter allows you to modify the template file path when a graceful fail (like a 404 error) occurs.
Usage
add_filter('graceful_fail_template', 'my_custom_graceful_fail_template'); function my_custom_graceful_fail_template($template) { // Your custom code here return $template; }
Parameters
$template
(string): The template file path to be modified.
More information
See WordPress Developer Resources: graceful_fail_template
Examples
Change the 404 template
Modify the 404 template with a custom one.
add_filter('graceful_fail_template', 'my_custom_404_template'); function my_custom_404_template($template) { // Set the custom 404 template file path $custom_template = get_stylesheet_directory() . '/custom-404.php'; // Check if the custom 404 template file exists if (file_exists($custom_template)) { return $custom_template; } return $template; }
Log 404 errors
Log the 404 errors with their request URLs.
add_filter('graceful_fail_template', 'log_404_errors'); function log_404_errors($template) { // Get the current request URL $request_url = $_SERVER['REQUEST_URI']; // Log the 404 error error_log("404 Error: " . $request_url); return $template; }
Redirect to the home page
Redirect users to the home page when a 404 error occurs.
add_filter('graceful_fail_template', 'redirect_to_home_on_404'); function redirect_to_home_on_404($template) { // Redirect to the home page wp_safe_redirect(home_url()); exit; return $template; }
Display a maintenance page
Show a maintenance page when a 404 error occurs.
add_filter('graceful_fail_template', 'display_maintenance_page_on_404'); function display_maintenance_page_on_404($template) { // Set the maintenance page template file path $maintenance_template = get_stylesheet_directory() . '/maintenance.php'; // Check if the maintenance page template file exists if (file_exists($maintenance_template)) { return $maintenance_template; } return $template; }
Notify the admin via email
Send an email to the admin when a 404 error occurs.
add_filter('graceful_fail_template', 'notify_admin_on_404'); function notify_admin_on_404($template) { // Get the admin email $admin_email = get_option('admin_email'); // Get the current request URL $request_url = $_SERVER['REQUEST_URI']; // Send an email to the admin wp_mail($admin_email, "404 Error on Your Website", "A 404 error occurred on the following URL: " . $request_url); return $template; }