Use ‘medium’ size with catch_that_image() function

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

3 Answers
3

When the first image is a WordPress image attachment.

in 3.6, there is an easier way.

function get_first_image_medium_size_url($post_id) {

 if(!$images = get_attached_images($post_id))
    return false;

 $first_image = current($images);

 if(!$src = wp_get_attachment_image_src($first_image->ID,'medium'))
    return false;

 $medium_url = current($src);

 return $medium_url;
}

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 function

function my_get_attached_images( $post_id = 0 ) {
    $post = empty( $post_id ) ? get_post() : get_post( $post_id );
    if ( empty( $post ) )
        return;

    $args = array(
        'post_parent' => $post->ID,
        'post_type' => 'attachment',
        'post_mime_type' => 'image',
        'posts_per_page' => -1,
        'orderby' => 'menu_order',
        'order' => 'ASC',
    );


    $children = get_children( $args );

    return (array)$children;
}

What 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

function get_first_image($content){
    if(!$content)
        return false;
    preg_match("@<img.+?src=[\"'](.+?)[\"'].+?>@",$content,$m);

    if($m[1])
        if(filter_var($m[1], FILTER_VALIDATE_URL))
            return $m[1];
    return false;
}

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.

function photon_image_url($orgin_url){
        $orgin_url = str_replace(array('http://','https://'),'',$origin_url);
        return 'http://i0.wp.com/'.$origin_url.'?w=50%';
}

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.

Leave a Comment