In which I explain how to parse the first image from a post

WordPress Wednesday: Grab First Image from Post

WordPressMany WordPress themes make use of a post’s featured image in their design. But what do you do if you have thousands of posts and not all of them have a featured image? With a bit of PHP regex hacking, you can parse the post’s content to grab the first image used in it and make that your featured image.

I’ll assume you’re using this in your header.php template, since that’s the place you’re most likely to need it, especially if you’re trying to get an image to use for Facebook or Twitter meta tags. This is just some pseudo-code, but it should be enough to get you started:

if ( is_single() ){
	if (have_posts() ) : while (have_posts() ) : the_post();
		$theme_post_content = get_the_content();
	endwhile; endif;

	if ( has_post_thumbnail() ){
		$social_image = get_the_post_thumbnail_url();
		$src = '';
		preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $theme_post_content, $image);
		$src = $image['src'];

		if ( strlen( $src ) ){
			$social_image = $src;
	echo '<meta property="og:image"		content="' . $social_image . '">';
	echo '<meta name="twitter:image"	content="' . $social_image . '">';

Credit: Stack Overflow user derp

Post the first comment:

I'll never share your email address and it won't be published.

What Is This? is the personal weblog of me, David Vincent Gagne. I've been publishing here since 1999, which makes this one of the oldest continuously-updated websites on the Internet.

A few years ago I was trying to determine what cocktails I could make with the alcohol I had at home. I searched the App Store but couldn't find an app that would let me do that, so I built one.


You can read dozens of essays and articles and find hundreds of links to other sites with stories and information about Ernest Hemingway in The Hemingway Collection.