Log and Monitor 404 Errors

Last updated 1 month ago

PHP
function my_plugin_log_404_errors() {
    if ( is_404() ) {
        $url = $_SERVER['REQUEST_URI'];
        $referer = isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : 'Direct Access';
        $log_message = '404 Error: ' . $url . ' - Referer: ' . $referer . ' - Date: ' . date( 'Y-m-d H:i:s' ) . "\n";
        
        // Log the error to a file
        $log_file = ABSPATH . 'wp-content/plugins/my-plugin-404-errors.log';
        file_put_contents( $log_file, $log_message, FILE_APPEND );
    }
}
add_action( 'template_redirect', 'my_plugin_log_404_errors' );

All code snippets are licensed GPLv2 or later unless otherwise stated.