In today's tutorial we are going to learn how you can display a page on your WordPress install if your website has a database error.
In WordPress it has a couple of default file names which it can grab and use if they are in the folder structure. Such as the footer.php, header.php and sidebar.php can all be accessed and displayed by different methods in your WordPress install.
There are other file names which WordPress will use to display default pages to the user on certain events. The example we are going to look at is the Database error page db-error.php.
WordPress Database Error
Normally when WordPress has a database error it will display this page, which explains that there is a problem with your database and WordPress can not connect.
The first thing you should check is your wp-config.php file, this is the file WordPress uses to store your database username and password. If something goes wrong with this file then the above message will be displayed.
But it's not very user friendly to the visitor of the site so you want to be able to keep the visitor on your theme but display a custom made error page for them.
All you have to do is create a new page and add this into your theme with the file name db-error.php. WordPress will automatically find this file and display this on your site instead of the default WordPress database error page.
Creating Your db-error.php File
Now we will see what you would need to add to this database error page.
First you want to start off by using PHP to change the http request on this page to a 503 Service Unavailable error, this is so if any crawlers come to the page they don't think your content has changed to this page.
Once you have displayed the 503 error it would be nice if the page continued to retry accessing the previous page just encase there was nothing wrong with the database it was just being overused at the current time and timing out. For this we add another header to retry the request.
After this you may want to send yourself an error alert to let you know there is currently a problem with your WordPress install.
Then you can add the standard HTML used by your theme and display any message that you want to your visitor.
<?php // WordPress database error page header('HTTP/1.1 503 Service Temporarily Unavailable'); header('Status: 503 Service Temporarily Unavailable'); header('Retry-After: 600'); // 1 hour = 3600 seconds // Alert yourself mail("email@example.com", "Database Error", "There is a problem with the database!", "From: Db Error"); ?> <!DOCTYPE HTML> <html> <head> <title>Database Error</title> </head> <body> <h1>Database Error Page</h1> </body> </html>