Many 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<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