Posted By

ghprod on 02/01/12


Tagged


Versions (?)

Simple WordPress Post Thumbnails with Regular Expressions


 / Published in: PHP
 

Find The Image

In pseudo code, what we need to do is:

  1. get the post content
  2. Use regex to find all images
  3. loop through all images and check if they are valid
  1. // get post content
  2. global $post;
  3. $content = $post->post_content;
  4.  
  5. // set default image value
  6. $theImageSrc = '';
  7.  
  8. // regex to find all images
  9. preg_match_all ('|<img .*?src=[\'"](.*?)[\'"].*?/>|i', $content, $matches);
  10.  
  11. $imageCount = count ($matches);
  12.  
  13. // needs to be a loop
  14. // Notice the += 2 in the for iterator
  15. // 0 = full image html tag
  16. // 1 = image path selected
  17. if ($imageCount >= 1) {
  18. for ($i = 1; $i <= $imageCount; $i += 2) {
  19. if (isset ($matches[$i][0])) {
  20. $theImageSrc = $matches[$i][0];
  21. break;
  22. }
  23. }
  24. }

Report this snippet  

You need to login to post a comment.