Get The First Image From a Post.php

Send Snippet To: Save this snippet to Code Collector Pro -- view all ian.k's snippets
language: PHP
license: Other

Code for Snippet:

                
/*
Let's say you wanted to use the post thumbnail feature of WordPress, but had a whole archive of posts that would take too much time to go through. For new posts, you can be specific and use the feature as intended. For old posts, you just want to use the first image it finds in the content for the thumbnail, or a default if none present.  Add this to functions.php or make a functionality plugin:
*/
 
function catch_that_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 = "/path/to/default.png";
  }
  return $first_img;
}
 
// To use it, use this code in the loop:
 
if ( get_the_post_thumbnail($post_id) != '' ) {
 
  echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">';
   the_post_thumbnail();
  echo '</a>';
 
} else {
 
 echo '<a href="'; the_permalink(); echo '" class="thumbnail-wrapper">';
 echo '<img src="';
 echo catch_that_image();
 echo '" alt="" />';
 echo '</a>';
 
}	
comments powered by Disqus

Info

Link to this snippet:


Download to Code Collector

To use the direct link to your snippet on CodeCollector.net either copy the html from the above section or drag the Download to Code Collector to where you would like to use it.

More Info:

Times Viewed: 470
Date Added: 2013-03-18 05:19:02
Last Modified: 2014-04-07 14:16:08

Web Analytics