catch_that_image() is a PHP function for WordPress that displays the first image of a post, so that you can create a gallery from your latest posts. It works quite well until someone goes crazy and uses special characters in their image filename.
You could try to establish file naming conventions, or you could stop being a masochist & modify the function. All that needs to be changed is a .* to [^>]*.
Here is the complete catch_that_image() function with the fix (it goes in your functions.php file):
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "/images/default.jpg";
}
return $first_img;
}
Call the function wherever you want in your theme files:
<?php echo catch_that_image() ?>
Easy!
Notes
- Original code & quick instructions from WPRecipes
- WordPress.org forum discusses the function: Retrieve first image from post
- A short explanation of how the code works from Smashing Magazine: 10 Useful WordPress Loop Hacks: #10. Create A Loop Of Images