wordpress100

catch_that_image() Fix

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

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>