I’ve this function, which I’m pretty sure a lot of you already know:
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];
return $first_img;
}
I would like to use the thumb, medium, etc sizes in the posts loop.
Do you guys have any idea how can I do this?
Cheers
When the first image is a WordPress image attachment.
in 3.6, there is an easier way.
get_attached_images is available in 3.6.
wp_get_attachment_image_src is available since 2.5.0 which will automatically get or scale the image attachment to specified size.
Since the 3.6 isn’t released yet, you may want to create your own
get_attached_images
functionWhat if the image isn’t a WordPress attachment type?
for example, you are linking to an flickr image.
Well, here is my version of catch_first_image
I think it is better than yours. Oftentimes, my heartbeat raises when I see the ob_* functions. hehe
How to resize the image?
I’d like to use WordPress Photon to do this thing.
note: this function is just to give you a general idea of how to use photon.
Of course, you can use Photon for both scenarios. You know, it is kind of a CDN service.
You will need to grab the image, get its ID, and then use
wp_get_attachment_image
to pick the appropriately sized image.And another version using the classes set on the image by default. This one has no extra database query but would fail if those classes are not set.
The function can also be called directly, without being used as a filter callback.
To replace the excerpt with the first image from the content requires a minor change. The
the_excerpt
filter is passed content like thethe_content
filter but there is no guarantee that the _post_content_ images will be in there.I also added a priority to the callback so that the filter runs late, hopefully after other filters so that the
the_excerpt
is completely replaced by the filter output.Sometimes I used a similar approach to your, so here is a simple function to be copied/pasted in your functions.php
As you can see it sets image Width = 100px and Image Height = 80px, I know that this isn’t the best solution as the image isn’t cropped or resized and it can be also an ‘heavy’ image but If the only thing you are looking for is a fast function that catches your first image… here it is.
After placing this code in your functions.php (without ) you’ll only have to write this:
where you want your ‘catched’ image to be shown.