How to Show First Image from Post Without Plugin
Automatically display thumbnail without using custom fields, with this simple function it will automatically retrieve first image of your post.
Automatically display thumbnail without using custom fields, with this simple function it will automatically retrieve first image of your post.
Open functions.php file of your theme and Paste following code and Save:
function show_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 = "/images/default.jpg"; // Define the Default image
}
return $first_img;
}
Now Download TimThumb.php script and place it in your theme directory.
After that open index.php file of your theme and paste the following code within the loop, where you want to display image.
<img src="<?php bloginfo('template_directory'); ?>/scripts/timthumb.php?src=<?php echo show_image() ?>&w=200&h=200&zc=1&q=100" alt="<?php the_title(); ?>"/>
To change the height and width of thumbnail change w= and h= variable
Thanks to Jean-Baptiste for sharing this code.