WordPress.org

Ready to get started?Download WordPress

Forums

Retreive First Image From Post (25 posts)

  1. westondeboer
    Member
    Posted 5 years ago #

    I have been looking around for this for ages. I have been using other post thumb plugins and just find them to bulky for what i wanted, too feature rich. I just wanted a basic grab the first image from a post and display it. Just add the below code to your functions.php file in your theme directory.

    // Get URL of first image in a post
    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];
    
    // no image found display default image instead
    if(empty($first_img)){
    $first_img = "/images/default.jpg";
    }
    return $first_img;
    }

    to call it just put <?php echo catch_that_image() ?> in your template file within the loop.

    I am using this in conjunction with http://code.google.com/p/timthumb to scale the image to what i want it to be. and i would just do

    <img src="/thumb.php?src=<?php echo catch_that_image() ?>&w=200&zc=1&q=200" alt="<?php the_title(); ?>"/>

  2. westondeboer
    Member
    Posted 5 years ago #

    I want to thank Travel Junkie from Is this an exploit in Post Thumb Revisited?, for the lead.

    Anyone know how i can optimize this, I am no php expert, just know how to hack php to make it work for me.

  3. artsaround
    Member
    Posted 5 years ago #

    Hey poil11,

    I keep running into a problem using timthumb and I'd be interested to know how you solved it. As far as I can tell timthumb balks at accepting a complete url as the img src

    for example in a small test file I can get this to work:
    <img src="timthumb.php?src=/wp-content/themes/ebc/no-image.gif&w=100&h=100&zc=1" alt="" />

    but not this:
    <img src="timthumb.php?src=http://www.blahblah.com/wordpress/wp-content/themes/ebc/no-image.gif&w=100&h=100&zc=1" alt="" />

    Your functions.php script however passes a full url when it echo's. Any suggestions, this has me stumped!

    Cheers

  4. nlex
    Member
    Posted 5 years ago #

    Very interesting, thanks for sharing, is it possible to specifiy an image : i'm not interested to make something automatic in this : want to generate the thumb myself and just 'link' it to a post (my site is not a blog siteā€¦)

  5. nlex
    Member
    Posted 5 years ago #

    What should i do to create a list of posts - as thumbs - of a specific category, using your method ?

  6. westondeboer
    Member
    Posted 5 years ago #

    <?php query_posts('category_name=special_cat&amp;showposts=10'); ?>
    
      <?php while (have_posts()) : the_post(); ?>
       <img src="/thumb.php?src=<?php echo catch_that_image() ?>&amp;w=200&amp;zc=1" alt="<?php the_title(); ?>"/>
      <?php endwhile;?>
  7. nlex
    Member
    Posted 5 years ago #

    thanks a lot :)

  8. royscheeren
    Member
    Posted 5 years ago #

    I'm having the same problem as artsaround.

    Any progress on this issue?

    thanx

  9. westondeboer
    Member
    Posted 5 years ago #

    The code would be:
    $first_img = str_replace('http://yourwebsite.com', '', $first_img);

    and you could just put it in there:

    // no image found display default image instead
    if(empty($first_img)){
    $first_img = "/images/default.jpg";
    }
    $first_img = str_replace('http://yourwebsite.com', '', $first_img);
    return $first_img;
    }
  10. carlosbronze
    Member
    Posted 5 years ago #

    im getting my image thumbnail ive inserted in the post
    can i change it so i get the image's link to the higher quality version?

  11. quech
    Member
    Posted 5 years ago #

    just wondering cause it doesn't seem to work with galleries (if all the post images are within a gallery). has anyone tried that?

  12. henri
    Member
    Posted 5 years ago #

    Nice piece of code!

    If you want to not display a default image but nothing if there is no image inside the post?

    Thanks for your help

  13. henri
    Member
    Posted 5 years ago #

    I found... Errase /image/default.jpg inside the function code and put this code inside your loop

    <?php if (catch_that_image()){ ?>
    <!-- Begin Thumb Container -->
    <div class="postthumb">
                  <a href="<?php the_permalink(); ?>">
                   <img src="<?php bloginfo('template_directory'); ?>/scripts/timthumb.php?src=<?php echo catch_that_image() ?>&w=580&h=150&zc=1&q=100" alt="<?php the_title(); ?>"/>
                  </a>
    </div><!-- End Thumb Container -->
    <?php }; ?>

    But there is a small bug in the code, the catch try to find not only jpg or png but also flash so it not display image. Is it possible to make a test on the filetype?

  14. jonnyburch
    Member
    Posted 5 years ago #

    I host my images externally (flickr) so cannot use timthumb - is there

    a) a different method of resizing that might work instead (the resizer in the 'sideposts' plugin works, maybe a hack on that?)

    or

    b) i wondered if there was a hack you could make on your (fantastic) catch_that_image function that would insert a '_t' onto the name of the image before the '.jpg' as thats the syntax flickr uses to generate a thumbnail. Even then it might not work, just an idea...

  15. jonnyburch
    Member
    Posted 5 years ago #

    a) a different method of resizing that might work instead (the resizer in the 'sideposts' plugin works, maybe a hack on that?)

    The function for which is

    function _sposts_thumbnails( $excerpt )
    {
    	global $post;
    
    	$settings = get_option('sideposts_widget');
    
    	$images = get_children( 'post_type=attachment&post_mime_type=image&post_parent=' . $post->ID );
    	if ( $images ) {
    		$img = array();
    		foreach( $images as $imageID => $imagePost ) {
    			$img[] = wp_get_attachment_image_src($imageID);
    		}
    		$thumb = array_pop($img);
    
    		$thumb_h = intval( (int) $settings['thumbnail'] * (int) $thumb[2] / (int) $thumb[1] );
    		$excerpt = apply_filters(	'sideposts_thumbnail',
    									'<img src="'. $thumb[0] .'" width="'. $settings['thumbnail'] .'" height="'. $thumb_h .'" class="alignleft" />')
    				 . $excerpt;
    	}
    
    	return $excerpt;
    }
  16. Alkorr
    Member
    Posted 5 years ago #

    Great hack but I have a problem: I get the first image of the post displayed exactly where I want with this code, but below it when I call <?php the_content(); ?> I get the same image again...

    Any solution? Thanks!

  17. mores
    Member
    Posted 4 years ago #

    Alkorr ... you either have a plugin active or you manually embedded the image inside the content.

  18. rliverman
    Member
    Posted 4 years ago #

    I had an issue using this for headlines where I didn't want to include a default image if the post had no image on its own. A friend helped me modify the code to accept your own sizing limits or to display nothing if an image was not found:

    function catch_that_image() {
      global $post, $posts;
      $first_img = '';
      $new_img_tag = "";
    
      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)){ //Defines a default image with 0 width
      $new_img_tag = "<img src='/images/noimage.jpg' width='0px' class='alignright' />";
      }
    
      else{
    	$new_img_tag = "<img src='" .  $first_img . "' width='75px' class='alignright' />";
    	}
    
      return $new_img_tag;
      }

    I.e. this will display a 75px thumbnail if the post has an image and nothing if it doesn't.

  19. dannbkk
    Member
    Posted 4 years ago #

    Ok I am having an issue:

    Seems as though the thumbnail gets added properly if I add an image through posting and when it stores itself locally: wp-content/uploads/2009/09/blue-2009-8b-1_12506756341.jpg .

    But If I put a image url location from another site the thumbnail doesn't appear in the initial post, so it doen't retrieve the first image from the post at all? Any ideas please?

  20. Piet
    Member
    Posted 4 years ago #

    this function works great indeed, however if your posts don't have an image, there is that default image.

    for a website i am developing i wanted more flexibility, in other words if there is an image i want to grab it and show the thumb, but if there is no image i want nothing at all.

    after a bit of searching i found that Justin Tadlock's Get the image plugin had a snippet of code that served to be very useful for this purpose.

    I created a new function in my functions.php that contained that code:

    function image_by_scan( $args = array() ) {
    
    	if ( !$post_id )
    		global $post;
    
    	preg_match_all( '|<img.*?src=[\'"](.*?)[\'"].*?>|i', $post->post_content, $matches );
    
    	if ( isset( $matches ) ) $image = $matches[1][0];
    
    	if ( $matches[1][0] )
    		return array( 'image' => $image );
    	else
    		return false;
    }

    I then replaced return array( 'image' => $image ); with return TRUE;

    In my index.php I then added the additional code:
    <?php if (image_by_scan('TRUE')) : ?>

    Works brilliantly, thanks so much for pointing me in the right direction!

  21. darthmortar
    Member
    Posted 4 years ago #

    Can you please explain how I cange the code so I can choose different images for different categories if their is no "first image in the post"?

    I have a category named "trailers" where I have posts with only an embed video, like YouTube, I want those posts thumb to be a different image.

    My second category is called "vardag" and contains personal things not related to "the other stuff" my blog is about, their I want another thumbimage, if their is no "first image in the post".

  22. joshrodgers
    Member
    Posted 4 years ago #

    Great piece of code. Is there a way where the function retrieves the first image in the post (the "Medium-Size" image), but links to the "Large-Size" image?

    Thanks,
    Josh :)

  23. akinoluna
    Member
    Posted 4 years ago #

    Using the first code at the top of this post, is there a way to set the size of the default image?

  24. bcWeb
    Member
    Posted 4 years ago #

    This works great.

    Thanks!

  25. 1xxooxx
    Member
    Posted 4 years ago #

    http://wordpress.org/support/topic/347903

    I just want to do an IF STATEMENT

    //
    look for the custom field "article_thumb" ->>
    if there is no "article_thumb" then look for first image in article
    if there is no image in the article ->>
    set "default.jpg" as the article image.
    end if
    //

    http://wordpress.org/support/topic/347903

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.