WordPress-Christmas-2010-18

Implement a 404 image in your Theme

Every good Theme comes with a 404.php for requests that don’t match any post or page. But what to do with missing images? They are requested per an <img> element usually, your visitors may never see the HTML template. Let’s use a 404 image.

I put the following code on top of my 404.php before get_header():

// @version 2011.12.23
// matches 'img.png' and 'img.gif?hello=world'
if ( preg_match( '~\.(jpe?g|png|gif|svg|bmp)(\?.*)?$~i', $_SERVER['REQUEST_URI'] ) )
{
    header( 'Content-Type: image/png' );
    locate_template( 'img/404.png', TRUE, TRUE );
    exit;
}

My 404 image is bright, eye-hurting red to let me see it easily during the tests.

404

License: WTFPL. Grab it while it’s red.

Comments are closed.

5 comments

  1. Pieter

    Wouldn't it be cool if you would use placeholdit to show an image with the current status code when something is going wrong?

    Like this one for a 404:
    http://placehold.it/350x250/FF0000/ffffff&text=404

    This one for a 403:
    http://placehold.it/350x250/0000FF/ffffff&text=403

    Etc.

  2. Thomas

    @Pieter: Use a very strict naming policy for your images and parse the requested path for width and height values. WordPress adds these values to resized files automatically, eg.: image-name-300x99.png.

    To add these parameters to not resized images you have to hook into 'sanitize_file_name' and change the name.

    But I wouldn’t bother. Set up an email notification for each 404 request and fix it immediately. That’s much more efficient.

  3. Rares

    Add an 'i' to preg_match to make the extension match case insensitive?

  4. Thomas

    @Rares Good catch! How could I miss that? Fixed. Thanks.

One pingback

  1. Adventskalender am 18. Dezember « F-LOG-GE