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.


Posted

in

by

Tags:

Comments

5 responses to “Implement a 404 image in your Theme”

  1. […] heute um Google Analytics. WPEngineer präsentiert einen kleinen Snippet zur Einbindung eines 404-Bildes für Bilder, die nicht gefunden werden – pfiffige […]

  2. Pieter Avatar

    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/350×250/FF0000/ffffff&text=404

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

    Etc.

  3. Thomas Avatar

    @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-300×99.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.

  4. Rares Avatar

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

  5. Thomas Avatar

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