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.
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.
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"); ?> <html> <head> <title>Database Error</title> </head> <body> <h1>Database Error Page</h1> </body> </html>
Get weekly updates to your email