This page was exported from Wordpress Joomla Freelancer Web Designer Web Developer Mumbai [ http://www.santoshkori.com/blog ]
Export date: Sun Dec 16 3:09:07 2018 / +0000 GMT

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.

[php]</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">[/php]

Once done, you can simply call the function within the loop to display the first image from the post:

[php]<?php echo catch_that_image() ?>[/php]

If you enjoyed this article, please consider sharing it!

</div>

 

 


Post date: 2011-08-19 15:23:07
Post date GMT: 2011-08-19 06:23:07
Post modified date: 2012-08-23 17:31:31
Post modified date GMT: 2012-08-23 08:31:31

Export of Post and Page has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com