[Trick] Get the first image in the post as avatar Posts

During the “move” This was my error when importing data from the old blog, it is up to their images are no media including avatar Posts (image thumbnail) when you set the featured image for the article. Fortunately, the image in its full article almost up to imgur.com then inserted featured image should not be lost but it would be up to the new, and I can not sit all day to download and reset the image to close 300 posts. So your trying to get the pictures in the article as always and his avatars found 2 how to make it display like this.

grab featured image for posts

How to 1: Using the code


First you copy the code below into function.php file, This is essentially 1 link function takes the first image in post.

function get_first_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];
 
  if(empty($first_img)) {
    $first_img = "/path/to/default.png";
  }
  return $first_img;
}

Note is inserted anywhere in the body but also the php tags in the file.
Then you open the index.php file (or if there content.php) function to call and find old photos featured image, mostly used the_post_thumbnail(). Specifically, this code to your index.php file.

<?php if ( has_post_thumbnail() ) { ?> 
	<?php echo '<div class="featured-thumbnail">'; the_post_thumbnail('featured',array('title' => '')); echo '</div>'; ?>
<?php } ?>

Instead of that period by:

<img src="<?php echo get_first_image(); ?>" alt="<?php the_title(); ?>" />

That's it for the homepage, Now if you want to search, the search by entering the tag or category (categories) also, the image must also be replaced with the same file archive.php, category.php, tag.php.

How to 2: Using the plugin

You can also make the content plugin to acquire images from up on the outside without using plugin External URL To Post Thumbnail, however, they used this way your code should not try, you try and commenting offline!

Article referenced in thachpham.com

Read english version here