Skip to Content
23 January, 2023

Example of WordPress plugin to check 404 errors

Table of Content

Sure, here is an example of how you can create a WordPress plugin to check 404 errors:

  1. Create a new folder in the wp-content/plugins directory and name it 404-checker.
  2. Inside that folder, create a new PHP file named 404-checker.php. This will be the main plugin file.
  3. In the 404-checker.php file, add the plugin information at the top, such as the plugin name, description, and version.
<?php
/*
Plugin Name: 404 Checker
Plugin URI: https://example.com/404-checker
Description: This plugin checks for 404 errors on your website and logs them in a custom database table.
Version: 1.0
Author: Your Name
Author URI: https://example.com
*/
  1. Next, create a custom database table to store the 404 error logs. You can use the dbDelta() function to create the table.
function create_404_log_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . '404_logs';

    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
        url varchar(255) NOT NULL,
        referrer varchar(255) NOT NULL,
        PRIMARY KEY  (id)
    ) $charset_collate;";

    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    dbDelta( $sql );
}
  1. Now, you can add a function that will be called whenever a page returns a 404 error. This function will log the error in the custom table created before.
function log_404_error() {
    global $wpdb;
    $table_name = $wpdb->prefix . '404_logs';

    $url = esc_url( $_SERVER['REQUEST_URI'] );
    $referrer = esc_url( $_SERVER['HTTP_REFERER'] );

    $wpdb->insert(
        $table_name,
        array(
            'time' => current_time( 'mysql' ),
            'url' => $url,
            'referrer' => $referrer,
        )
    );
}
  1. Finally, you need to activate the plugin and register the function to be called on 404 errors. You can do this by adding the following code at the bottom of the plugin file:
register_activation_hook( __FILE__, 'create_404_log_table' );
add_action( 'wp_head', 'log_404_error' );

This is just an example, you can customize the plugin as per your requirement. Please note that this code is for demonstration purposes only, and you should thoroughly test and debug your plugin before using it on a live website. If you are not familiar with these technologies, I would recommend hiring a WordPress developer with experience in plugin development to assist you.

Please let me know

Insights

The latest from our knowledge base