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>
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

Wordpress Freelancer, Joomla Freelancer Web designer Mumbai india, Wordpress web developer India, Joomla Web developer india, Outsourcing web project india mumbai

By Santosh Kori Published: October 10, 2012 Professional Freelance Website developer 5 stars based on 65 reviews Total time: 24 hour 00 min Wordpress Joomla XHTML CSS jQuery HTML5 eCommerce CSS3 ☞ Offers low cost freelance web designing, asp php asp.net web development services from Mumbai India. Freelance web designer & developer Mumbai India.

I AM NOT AVAILABLE FOR WEB DESIGN & DEVELOPMENT PROJECTS