• Resolved soppezzo

    (@soppezzo)


    Hi there!
    I´m using this function to get the images of the posts to above the post titles. This works great! But right now, I need to do exactly the same but with videos (for example Youtube), so, how should I do? Here I copy the function I´m using.

    [ Moderator note: please wrap code or markup snippets in backticks or use the code button. ]

    function catch_that_image() {
      global $post, $posts;
      $first_img = '';
      ob_start();
      ob_end_clean();
      $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
      $first_img = $matches [1] [0];
    
      if(empty($first_img)){ //Defines a default image
        $first_img = "/images/default.jpg";
      }
      return $first_img;
    }

    Please be good, I´m a Web Designer!:D
    Thanks in advance!

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    Depends on how the video is embedded. If using iframes, you’ll get the source url just by changing img in preg_match_all() to iframe.

    You’ll also need to change the html that uses the returned url from an img tag to a iframe tag. Don’t forget the iframe tag has a separate closing tag, unlike the img tag.

    Thread Starter soppezzo

    (@soppezzo)

    Hi again!! Thanks very much for the tips! I had to ask for some extra php help but we figured it out. Here I leave the code:

    In functions.php:

    function catch_that_iframe() {
      global $post, $posts;
      $first_img = '';
      ob_start();
      ob_end_clean();
      $output = preg_match_all('/<iframe.+src=[\'"]([^\'"]+)[\'"].*><\/iframe>/i', $post->post_content, $matches);
      $first_img = $matches [1] [0];
    
      return $first_img;
    }

    In the html:

    <?php
    	$topimg = catch_that_image(); // Find first image of Post
    								$topiframe = catch_that_iframe();
    
    	if ($topimg) {
    									echo('<img src="'.$topimg.'">');
    	} else if ($topiframe) {
    									echo('<iframe src="' . $topiframe . '"></iframe>');
    	} else {
    									echo('<img src="/images/default.jpg">');
    	}
    ?>

    This means that if the post contains an image, then put it first. If the post contains a video, then also put it first. But if the post contains nor image neither a video, then, show a “default image”.

    Hope this can help anyone else!
    Thanks!!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Modifying the "catch_that_image()" function for videos’ is closed to new replies.