Say you want to use the featured image (post thumbnail) that WordPress provides, but you have an archive with many posts and it would take a long time to add that featured image to each of them.
For new posts you can use the featured image in the standard way, but for old posts you want to use the first image in the post content as the featured image, or a default image if there are no images in that specific post. Add the following code to functions.php:
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+?src=['"]([^'"]+)['"].*?>/i', $post->post_content, $matches);
$first_img = $matches[1][0];
if(empty($first_img)) {
$first_img = "/path/to/default.png";
}
return $first_img;
}And to use this inside the WordPress loop:
if ( get_the_post_thumbnail($post_id) != '' ) {
echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">';
the_post_thumbnail();
echo '</a>';
} else {
echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">';
echo '<img src="';
echo catch_that_image();
echo '" alt="" />';
echo '</a>';
}For more on WordPress image handling, see Image Sizes in WordPress.