Home » Tips-n-Tricks » How to Get the first image from the post and display it in WordPress

<div>
Most WordPress users are using custom fields to display thumbs on their blog homepage. It is a good idea, but do you know that with a simple php function, you can grab the first image from the post, and display it. Just read on.
First, paste this function on your <em>functions.php</em> file.
</div>
<div id="_mcePaste">function catch_that_image() {</div>
<div id="_mcePaste">global $post, $posts;</div>
<div id="_mcePaste">$first_img = '';</div>
<div id="_mcePaste">ob_start();</div>
<div id="_mcePaste">ob_end_clean();</div>
<div id="_mcePaste">$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);</div>
<div id="_mcePaste">$first_img = $matches [1] [0];</div>
<div id="_mcePaste"></div>
<div id="_mcePaste">if(empty($first_img)){ //Defines a default image</div>
<div id="_mcePaste">$first_img = "/images/default.jpg";</div>
<div id="_mcePaste">}</div>
<div id="_mcePaste">return $first_img;</div>
<div id="_mcePaste">}</div>
<div id="_mcePaste">
Once done, you can simply call the function within the loop to display the first image from the post:
<?php echo catch_that_image() ?>
If you enjoyed this article, please consider sharing it!
</div>

Array ( [0] => Tips-n-Tricks, Wordpress )

Leave a comment

2 Comments.

  1. I got one problem.. Please help me… i still can’t create sitemap in myblog… i dontknow why.. more time i create still appear status like this… ” please make sure you change cmod to 777 or 775.. but, when i changed to this cmod still appear same status.. :( … Please help me…

    Watch Series Online Free