Simple WordPress Post Thumbnails with Regular Expressions

These days everyone with a blog understands the importance of thumbnail images. Three years ago it was common place to have exclusively text, but now a nice image is a requirement. As such the process of implementing the image needs to be made easier.

With my WordPress themes, Elemental in particular, I have simplified things as much as possible. You can set your own thumbnail using the WordPress featured image functionality, or you can use custom fields (which is generally considered 'old fashioned' despite being the height of technology just 2 years gone). However my favorite methods is the automatic thumbnails - which is the system I use most often on my websites.

The automatic thumbnails method involves the theme working out what images are used in the post, and then resizing one of these. The benefit of this being that all I have to do is embed an image into a post, and my thumbnail will display.

Obviously, being the developer behind TimThumb, I use TimThumb for all of my thumbnail requirements. This means the hard part is working out what image to resize, and this is where I use Regular Expressions (often shortened to Regex).

A regular expression is a complicated looking string of text and punctuation that creates rules used by a computer to find information.

Before I show how I do this I feel I should point out that I am not an expert at Regex. I know the fundamentals, but working out proper regular expressions is an art form in itself, and it's not one I am interested in learning. If you ever need to write a regular expression, then just Google it. 9 times out of 10 someone will have done what you want!

Find The Image

In pseudo code, what we need to do is:

  1. get the post content
  2. Use regex to find all images
  3. loop through all images and check if they are valid

Which in PHP looks something like:

	// get post content
	global $post;
	$content = $post->post_content;

	// set default image value
	$theImageSrc = '';

	// regex to find all images
	preg_match_all ('|<img .*?src=[\'"](.*?)[\'"].*?/>|i', $content, $matches);

	$imageCount = count ($matches);

	// needs to be a loop
	// Notice the += 2 in the for iterator
	// 0 = full image html tag
	// 1 = image path selected
	if ($imageCount >= 1) {
		for ($i = 1; $i <= $imageCount; $i += 2) {
			if (isset ($matches[$i][0])) {
				$theImageSrc = $matches[$i][0];
				break;
			}
		}
	}

Default Image

If you wanted to supply a default image when using this code then you could easily add the following code after the image detection above.

	if (empty ($theImageSrc)) {
		$theImageSrc = 'path/to/default/image.jpg';
	}

What Next?

So what can you do with this? What I did in Elemental is wrap that code into a function, and then combine it with the code I created in my post about how to use TimThumb with WordPress MultiSite. The resulting url can then be used as the image src with TimThumb, and that image can be used as a post thumbnail.

I actually combined this with a variety of other methods for grabbing the post image which means that however you attach an image to a post, it will be found. You can read about the different methods I use on this post on Elemental Hub.

Share This...

TimThumb Technical Support

Need help with getting TimThumb to work? Check here for my prices.

Support ›
About The Author

Ben Gillbanks

Web Designer, Video Gamer, Blogger, and part time Entrepreneur. Read More

8 thoughts on “Simple WordPress Post Thumbnails with Regular Expressions

  • Reply ›
    Terry

    Regular expression is hard for normal users, but the PHP code helps a lot, thank you.

    April 23, 2011

  • Reply ›
    Lucian Apostol

    This is great combined with a script that will automatically crop the image. Forcing the resize of the image in html/css will make the image ugly.

    May 8, 2011

  • Reply ›
    zaryl

    hai Ben,
    though this might sound silly...
    if one of my posts which using timthumb to generate thumbnail image as default but didn't have any image in it, how am I going to replace it with other image?

    thanks..

    June 21, 2011

    • Reply ›
      Ben

      currently there is no way to do default images with TimThumb, you would need to build it into your theme. I have added a quick snippet to the article above to show how I would do this :)

      June 24, 2011

  • Reply ›
    Calgary Web

    WRT Lucian's post. If an image is already the correct size, the server will still try to resize / crop it, and will blur it. CSS resize gives much better results as far as sharpness and crispness goes.

    October 29, 2011

  • Reply ›
    James

    Hi. I'm using timthumb on my site. He's cropping image too much in preview screen. How can I make a different cropping heigh and width ?

    http://woodyart.kiev.ua/Project/xellouin/

    November 2, 2011

  • Reply ›
    Will

    It would be better to define the default image at the start, instead of an empty variable:

    // get post content
    global $post;
    $content = $post->post_content;

    // set default image value
    $theImageSrc ='path/to/default/image.jpg';

    ....

    August 7, 2012

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="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Websites linking here

  1. Favicon for http://www.google.com/s2/favicons?domain=dumaslab.com 50 Unique and Informative wordpress tutorial showcase | DumasLab.com

My Projects

TimThumb - Image Resize Script TimThumb

Image Resize Thumbnail Script

WPVote - WordPress Social Voting WPVote.com

WordPress Social Voting Site

About me

About BenMy name is Ben Gillbanks. I'm a lover of Video Games, WordPress, Web Development and everything in between.

I have been working on the internet since 1998, and working with computers even longer. I am a hardcore Nintendo fanboy and have owned most of their consoles at one stage or another.

Read more about me on my about page.

Random Link-outs

Keep Updated

Subscribe to RSS

Stay Updated

Binary Moon

WordPress and Web Development › home of Ben Gillbanks