Search code examples
wordpresspostsorl-thumbnail

Show attached media image if no thumbnail image detected


I'm using

 if ( has_post_thumbnail() ){}

to check if the post have thumbnail image, but this

 echo get_attached_media('image', $post->ID);

display the word

 Array

I need to show the attached image


Solution

  • If you are trying to get just one image in the post and use it as a thumbail, you might want to try this one:

    Add this to you're functions.php :

    // Get URL of first image in a post
    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];
    
    // no image found display default image instead
    if(empty($first_img)){
    $first_img = "/images/default.jpg";
    }
    return $first_img;
    }
    

    To call it just put

    <?php echo catch_that_image() ?>

    in your template file within the loop.

    I found this brilliant code from this forum thread. Saved me a lot of times.