Grab first image on post - wordpress


/ Published in: PHP
Save to your folder(s)

Use this to grab the first image in a post


Copy this code and paste it in your HTML
  1. function catch_that_image() {
  2. global $post, $posts;
  3. $first_img = '';
  4. $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  5. $first_img = $matches [1] [0];
  6.  
  7. if(empty($first_img)){ //Defines a default image
  8. $first_img = "/images/default.jpg";
  9. }
  10. return $first_img;
  11. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.