rakeshr

first image of a wordpress post.

Jun 23rd, 2014
369
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.64 KB | None | 0 0
  1.  <?php if (have_posts()) : ?>
  2.  <?php while (have_posts()) : the_post(); ?>
  3.  
  4.  <?php
  5.  $szPostContent = $post->post_content;
  6.  $szSearchPattern = '~<img [^\>]*\ />~';
  7.  
  8. // Run preg_match_all to grab all the images and save the results in $aPics
  9. preg_match_all( $szSearchPattern, $szPostContent, $aPics );
  10.  
  11.  // Check to see if we have at least 1 image
  12.  $iNumberOfPics = count($aPics[0]);
  13.  
  14. if ( $iNumberOfPics > 0 ) {
  15.    // Now here you would do whatever you need to do with the images
  16.    // For this example the images are just displayed
  17.    for ( $i=0; $i < $iNumberOfPics ; $i++ ) {
  18.         echo $aPics[0][$i];
  19.    };
  20. };
  21.  
  22. endwhile;
  23. endif;
  24. ?>
Advertisement
Add Comment
Please, Sign In to add comment