Wordpress ; Get the first image from the post and display it


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

It allows you to automatically get the first image from the current post, and display it.


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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.