Question

I write this code for show thumbnails from related posts. If related post has no thumbnail, it should show first pict from his content:

     $output .= "<a href=\"".get_permalink($related_post->ID)."\">";
          if(get_the_post_thumbnail($related_post->ID)) {
              $output .= get_the_post_thumbnail($related_post->ID, $options['thumbnail_size']);
          } else {
              $output .= catch_image( $related_post->ID );
          }
     $output .= "</a>";

and in function.php I have this function:

   function catch_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)) {
            $first_img = "url for noimage.jpg";
       }

   return $first_img;
   }

But this give me just first image from This post, not from related post. How can I take content which I need?

Was it helpful?

Solution

Try with this function:

 function catch_image($post_id) {

   $first_img = '';
   ob_start();
   ob_end_clean();
   $related_post = get_post($post_id);
   $content = $related_post->post_content;
   $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches);
   $first_img = $matches[1][0];

   if(empty($first_img)) {
        $first_img = "url for noimage.jpg";
   }

   return $first_img;
 } 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top