The get_404_template() WordPress PHP function retrieves the path of the 404 template in the current or parent template.
Usage
$four04_template = get_404_template();
Parameters
- None
More information
See WordPress Developer Resources: get_404_template
Examples
Display a custom 404 message
// If the 404 template is available, include it
if ($template = get_404_template()) {
require_once($template);
} else {
// Fallback: Display a simple custom 404 message
echo '<h1>Oops! Page not found.</h1>';
}
Custom 404 template location
// Filter the location of the 404 template
function my_custom_404_template($template) {
return get_stylesheet_directory() . '/my-404.php';
}
add_filter('404_template', 'my_custom_404_template');
Check if 404 template exists
// Function to check if the 404 template exists
function has_404_template() {
return (bool) get_404_template();
}
// Usage: Check if the 404 template exists and display a message accordingly
if (has_404_template()) {
echo '404 template exists';
} else {
echo '404 template does not exist';
}
Add a 404 template from a plugin
// Function to add a 404 template from a plugin
function plugin_404_template($template) {
if (!get_404_template()) {
return plugin_dir_path(__FILE__) . 'templates/404.php';
}
return $template;
}
add_filter('404_template', 'plugin_404_template');
Log 404 errors
// Log 404 errors to a custom log file
function log_404_errors() {
if (is_404()) {
$log = date('Y-m-d H:i:s') . ' - ' . $_SERVER['REQUEST_URI'] . "\n";
file_put_contents(get_template_directory() . '/404-log.txt', $log, FILE_APPEND);
}
}
add_action('wp', 'log_404_errors');