Search This Blog

Friday, 22 June 2012

Get first Image from Post content in Wordpress

Add this function to functions.php at bottom
 
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)){ //Defines a default image
    $first_img = "/images/default.jpg";
  }
  return $first_img;
}
 
Below code will display image URL from content of the post 
<?php echo catch_that_image(); ?>

No comments:

Post a Comment