Premium Wordpress Themes

How to Get the First Image From The Post in WordPress

wordpress imageThe wordpress is very popular these days, and a lot people love magazine style wordpress themes, and the most important designs are feature gallery slidshow and post thumb images(small image, and you know a lot magazine wp templates are using this.). If you want to get the first image From Posts On Your Home Page, here are 2 ways.

1 The first idea is automatically retrieving the first image from a post and using it as a thumbnail (the original images are OK)

  1. First of all,find and open the functions.php file in your theme.
  2. paste this function on your functions.php file.
    function catch_that_image() {
      global $post, $posts;
      $first_img = '';
      $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
      $first_img = $matches [1] [0];
      if(empty($first_img)){ //Defines a default image
        $first_img = "/images/default.jpg";
      return $first_img;
  3. Save the functions.php file.
  4. On your blog home page (index.php), Once done, you can simply call the function within the loop to display the first image from the post:
    <?php echo catch_that_image() ?>

The bad thing of this idea is you can not get the image alt.

2 The second idea is to use wordpress custom fields to display a thumbnail / orignal image on their blog home page(I love show original images because this is good for seo)

  1. Login your wordpress admin panel, click “Post ->Add New” find the “custom fields”
  2. Create a new custom field name “image”, the value is your images url
  3. Add this to the index.php to the loop, just under the post title (just like under </h1></h2>)
    <img src="<?php $values = get_post_custom_values("image"); echo $values[0]; ?>" alt="<?php the_title(); ?>" width="240px"/>