davidgagne.net

  • About
  • Archives
  • Twitter
  • Facebook
  • bartender.live
  • GitHub
  • LinkedIn

WordPress Wednesday: Grab First Image from Post

February 8th, 2017 @ 6:36 am PST

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();
	}
	else{
		$src = '';
		preg_match('/<img.+src=[\'"](?P.+?)[\'"].*>/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

More posts tagged:
PHP / Programming / wordpress / wordpresswednesday

More posts categorized:
Programming

More posts from:
February 2017 / 2017

Post navigation

Previous Post
Previous Post Ernest Hemingway: American Sniper?
Next Post
Next Post Goodbye, Trader Vic’s

Search


Switch to FreshBooks

Switch to FreshBooks

I switched from QuickBooks to FreshBooks in 2015 and am so glad I did. Everything about their billing system is easier.

  • Take Control of Your Invoices

© David Vincent Gagne. All rights reserved. Custom WordPress Theme by Jacket Industries.