On my personal blog I put an image at the top of each post. I’ve wanted to do this with WordPress’ Featured Image function, but haven’t gotten around to it, yet.
When I do, what will happen to all those old posts? What will happen when I try to use WordPress’ post thumbnail feature?
For my old posts, I will want to use the first image that’s found in the content or some sort of default if no image is present.
Of course, this is one example of many reasons why you would want to do this!
Here’s the code:
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/
$first_img = $matches[1][0];
if(empty($first_img)) {
$first_img = "/path/to/default.png";
}
return $first_img;
}
As usual, drop this in your theme’s function.php or bundle it up in a functionality plugin.
To grab the image, use this in the loop:
if ( get_the_post_thumbnail($post_id) != '' ) {
echo '';
the_post_thumbnail();
echo '';
} else {
echo '';
echo '';
echo '';
}
Nifty.
[via CSS Tricks]
marc says
Thanks for the post, but i get the last image insted of the first one. Do you know what can be? Thank you!