Flexible way of grabbing first image from a Post

Many WordPress themes nowadays show an image of a Post (a thumbnail) on the home page which can make the website more appealing to the visitor.

You can of course install one of the many plugins that accomplish this, or you could do something with custom fields, but of both we are not big fans.

Another way of showing a smaller version of the Post’s image is by adding a function to your functions template, like:

// Get URL of first image in a post
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];

// no image found display default image instead
if(empty($first_img)){
$first_img = "/images/default.jpg";
}
return $first_img;
}

The above function grabs the first image from the Post and outputs that. If there is no image in the Post, the function outputs a default image (you need to upload that separately). If you use this in conjunction with the timthumb script you can insert this line in your index.php to show the image:

<img src="/scripts/timthumb.php?src=<?php echo catch_that_image() ?>&w=200&zc=1&q=200" alt="<?php the_title(); ?>"/>

The big disadvantage of the above example however is that there is always an image; if your Post doesn’t have an image, there is that default image showing up. Now of course this is pure personal taste. We wanted a bit more flexibility, in other words if there is an image we want to grab it and show the thumb, but if there is no image we want to show nothing at all.

After a bit of searching we found that Justin Tadlock’s Get the image plugin had a snippet of code that served to be very useful for this purpose.

We created a new function in our functions.php that contained that code:

function image_by_scan( $args = array() ) {

	if ( !$post_id )
		global $post;

	preg_match_all( '|<img.*?src=[\'"](.*?)[\'"].*?>|i', $post->post_content, $matches );

	if ( isset( $matches ) ) $image = $matches[1][0];

	if ( $matches[1][0] )
		return array( 'image' => $image );
	else
		return false;
}

We then replaced line 11 return array( 'image' => $image ); with return TRUE;

Combined with the timthumb script your index.php can now become like this:

<?php get_header(); ?>
	<div id="content">
		<?php if (have_posts()) : ?>
		<?php while (have_posts()) : the_post(); ?>
		<div class="post-box">
			<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
				<div class="postthumb">
					<?php if (image_by_scan('TRUE')) : ?><a href="<?php the_permalink() ?>"><img src="<?php echo bloginfo('template_url'); ?>/scripts/timthumb.php?src=<?php
                    echo catch_that_image() ?>&amp;w=100&amp;h=100&amp;zc=1" alt="<?php the_title(); ?>" width="100" height="100"  /></a>
					<?php else : ?>
					<?php endif; ?>
				</div> <!--close div class postthumb-->
				<h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
				<small><?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?> --></small>
				<div class="entry">
					<?php the_excerpt('Read the rest of this entry &raquo;'); ?>
				</div><!--end entry class-->
				<div class="postmetadata">
					<p><?php edit_post_link('Edit', '', ' | '); ?> Posted in <?php the_category(', ') ?> | <?php comments_popup_link('No Comments', '1 Comment', '% Comments'); ?> | <?php if(function_exists('the_views')) { the_views(); } ?></p>
				</div><!--end postmeta class-->
			</div><!--end post class-->
		</div><!--end post-box class-->
			<?php endwhile; ?>
			<div class="navigation">
				<?php if(function_exists('wp_pagenavi')) { wp_pagenavi(); } ?>
			</div><!--end navigation class-->
			<?php else : ?>
				<h2 class="center">Not Found</h2>
				<p class="center">Sorry, but you are looking for something that isn't here.</p>
				<?php get_search_form(); ?>
			<?php endif; ?>
	</div><!--end content-->
<?php get_sidebar(); ?>

<?php get_footer(); ?>

Do you use thumbnails on your index.php and how do you grab them?

Back to Top

8 thoughts on “Flexible way of grabbing first image from a Post

  1. I do not grab the post image, WordPress now has it’s own powerful thumbnail code, you can enable this with just a few lines of code, a portfolio theme I have developed the home page can display four post columns, thumbnail or excerpt

    		<!-- Start CMS-Lite code Add our post image and excerpt to the category list if it has one -->
    		<?php  if ( has_post_thumbnail() ) { ?>
    			<div class="cms-image">
    				<a href="<?php the_permalink() ?>" > <?php the_post_thumbnail(); ?></a>
    			</div>
    			<?php the_excerpt(); ?>
    		<?php } else { ?>
    			<?php if (is_search()) the_excerpt(); else the_content(__('Read the rest of this entry &raquo;', 'kubrick')); ?>
    		<?php } ?>
    		<!-- End CMS-Lite  -->
    

    Theme download and details: http://digitalraindrops.net/demo/wordpress/cms-lite/2010/02/27/cms-portfolio-theme/

    David

    • I’m sure there is a way to do many things with it, but keep in mind that this “idea” is something of already 2 years ago. I am sure there are many other ways of accomplishing what you’re looking for.

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>