Grab the first image from posts and display it in WordPress
Written by Clement Faria on March 24, 2012 under Web Development.
If you visit alot of modern WordPress websites, you will notice that the posts on the home page as well as other pages, include thumbnail images. One of the most popular methods to accomplish this, is by using custom fields to display the thumbs on the page. While this method is good, there is also another and quite simple php function, in which you can grab and display the first image, that you inserted into a post. This way you can insert your images into your posts like normal, and do not have to worry doing extra work.
The first thing that must be done, is to paste the code below into your functions.php file.
function grab_image() {
global $post, $posts;
$first_image = ”;
ob_start();
ob_end_clean();
$output = preg_match_all(‘/<img.+src=[\'"]([^\'"]+)[\'"].*>/i’, $post->post_content, $matches);
$first_image = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_image = “/images/default.jpg”;
}
return $first_image;
}
This function basically checks the post content, then selects the first image. If there no image is found, it will display a default image.
In your template, you can call the function inside the loop to display the first image.
<?php echo grab_image() ?>
You can also use css to style your thumbnails to format it better and give it a great look. Please enjoy and use this funtion in your wordpress projects.





Comments