Support » Fixing WordPress » Pulling video and images from posts with regular expressions

  • I was looking for a code or plugin that would pull all the images (jpgs/gifs/pngs) as well as videos (vimeo/youtube) from a post, as they appear chronologically in a post, to display on index.php.

    I think I have a half decent grasp of PHP but regular expressions are where I get confused. To isolate the image/video urls with preg_replace and regular expressions is where I’m getting lost.

    I know you can create a custom field where I could input the vimeo id, another for the youtube id, and another for any image url, but there may be some cases where I have lots of images and video and it seems like an awkward approach.

    Does anyone have any tips or could someone point me in the right direction for tackling this? Maybe custom fields is the way I should go, not sure. Or maybe a theme already exists with this kind of function?

    Thanks

Viewing 1 replies (of 1 total)
  • Thread Starter ssccdd

    (@ssccdd)

    was able to get the images working with this code in the loop on index.php, but I can’t seem to figure out an equivalent for vimeo videos:

    <?php
         // IMAGES
         $allPost = $post->post_content; 
    
         $images = array();
         preg_match_all('/(img|src)\=(\"|\')[^\"\'\>]+/i', $allPost, $media);
         unset($allPost);
         $allPost=preg_replace('/(img|src)(\"|\'|\=\"|\=\')(.*)/i',"$3",$media[0]);
         foreach($allPost as $url)
         {
              $info = pathinfo($url);
              if (isset($info['extension']))
              {
                   if (($info['extension'] == 'jpg') ||
                   $info['extension'] == 'jpeg') ||
                   ($info['extension'] == 'gif') ||
                   ($info['extension'] == 'png'))
                   array_push($images, $url);
              }
              }
    
         $numImages = count($images);
    
         for ( $i = 0; $i < $numImages; $i ++) {
              echo '<div class="postphotowrapper">';
              echo '<img src="'.$images[$i].'">';
              echo "</div>";
         }
    ?>
Viewing 1 replies (of 1 total)
  • The topic ‘Pulling video and images from posts with regular expressions’ is closed to new replies.