If you attempt to access the URL of a non-existent image file on a website – say a jpg, png or gif file – you will usually be redirected to the 404 error page. If the image is embedded via an HTML img tag, this will normally result in your browser displaying a missing image icon.
Instead, we can handle this in a more elegant way by creating a special 404 Error image which will be returned when someone attempts to request a non-existent image file on your website.
All we have to do is:
- Create the 404 Error Image file and save it in PNG format as “404.png”. Alternatively, you can use the one above.
- Upload the file to the images folder within your WordPress theme
- Your WordPress theme folder should have a file 404.php. This is the template file that is used to generate the 404 error page. Insert the following snippet of PHP code after the PHP opening tag at the very top of this file.
//If they have tried to access an invalid image file, return a 404 image if ( preg_match( '~\.(jpe?g|png|gif|svg|bmp)(\?.*)?$~i', $_SERVER['REQUEST_URI'])) { $image404 = locate_template('images/404.png'); if (!is_null($image404)) { $fp = fopen($image404, 'rb'); header( 'Content-Type: image/png' ); header( 'Content-Length: ' . filesize($image404)); fpassthru($fp); } exit; }
Other Notes
The idea for this post was inspired by the following links:
Implement a 404 image in your Theme
The snippet of code they provided didn’t work for me, so I created my own.
http://wordpress.org/extend/plugins/wp-404-images-fix/
I haven’t tried this plugin, but if you don’t want to go to the trouble of modifying your theme files, this might provide a simpler alternative.
|
Add Your Comments