WordPress tips and tricks – custom 404 (error) pages
One of the more underused features in wordpress themes is the ability to create and modify the 404 page – so to try to rectify this I thought I’d run through what I do with 404 pages on Binary Moon (and my other WordPress site). I use this simple technique to try to make errors a bit more and helpful for people who have ended up at the wrong place. I’m hoping that not too many people see the 404 page but just in case here is what I’ve done.
Basically I duplicate a normal page template and name it “404.php”. I then remove “the loop” and add some some static code which explains that there has been an error and a few possible solutions (archives, search).
Finally I use query_posts to add in a new loop which displays links to the 5 most recent articles. Below is the actual code I use on this site for my 404 page (you can see it in action here – http://www.binarymoon.co.uk/9837489)
<?php get_header(); ?> <h1>404 - Doh!</h1> <p>Something has gone wrong and the page you're looking for can't be found.</p> <p>Hopefully one of the options below will help you</p> <ul> <li>You can search the site using the search box to the left</li> <li>You could visit <a href="http://www.binarymoon.co.uk/">the homepage</a></li> <li>Maybe what you're looking for is </a><a href="http://www.binarymoon.co.uk/archives/">in the Archives?</a></li> <li>Or you could have a look through the recent posts listed below, maybe what you're looking for is there</li> </ul> <h3>Recent Posts</h3> <ul> <?php query_posts('posts_per_page=5'); if (have_posts()) : while (have_posts()) : the_post(); ?> <li><a href="<?php the_permalink() ?>" title="Permalink for : <?php the_title(); ?>"><?php the_title(); ?></a> <?php endwhile; endif; ?> </ul> <?php get_footer(); ?>
Something you may want (need?) to do is to add your new 404 page to your .htaccess file so that when a bad/ non-existant page is accessed the visitor gets your custom 404 instead of your webhosts ugly page. To do this all you need to do is grab your .htaccess file and add the following code.
ErrorDocument 404 /index.php?error=404
That’s it – easy as can be.
Now nobody has an excuse not to have a helpful, attractive 404 page. Of course it doesn’t have to be helpful (but that IS nice) but can also be funny or amusing – maybe you can find some inspiration here at area 404. Be sure to let me know if you have an unusual or unique 404 page as well.