WordPress Thumbnails / Featured Images from Post Content

If you end up in a situation where it is either too much work to add thumbnails / featured images to posts, or you have imported posts and the images are only set in the content, then you need a quick way of using the images in the content as thumbnails.

This “hack”, works here on a child of the Sparkling theme. It may need modifying for other themes.

These thumbnails are designed to be shown next to extracts, not full contents.

The change is in the “content.php” file.

Find the entry-content div:

<div class="entry-content">
<?php
if ( get_theme_mod( 'sparkling_excerpts' ) == 1 ) :
the_excerpt();
else :

Insert a regex to find the first image tag in the page content, clean it a little and echo an img tag if an image was found, so you end up with:

<div class="entry-content">
<?php
$o = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$fimg = $matches [1] [0];
$fimg = ltrim($fimg, '[');
$fimg = rtrim($fimg, ']');
if (!(empty($fimg))) {
echo "<img src='$fimg' class='extractthumb_alignleft' />";
}
?>
<?php
if ( get_theme_mod( 'sparkling_excerpts' ) == 1 ) :
the_excerpt();
else :

Yes, the code could be cleaned up, easily, but it works for now.

For CSS, just add something along the lines of:

img.extractthumb_alignleft {
width: 25%;
float: left;
margin: 0 10px 10px 0;
}

 

This is, by no means, a “professional” fix but it works as a quick fix for me.

Related Posts