first image from the wordpress post and display it, not working

Discussion in 'PHP' started by pix582, Sep 21, 2012.

  1. #1
    i am using
    function get_first_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;
    }
    Code (markup):
    with
    <?php echo get_first_image() ?>
    Code (markup):
    but on my home page, its just showing the image link

    can any one help out?
    thanks.
     
    pix582, Sep 21, 2012 IP
  2. plussy

    plussy Peon

    Messages:
    152
    Likes Received:
    5
    Best Answers:
    9
    Trophy Points:
    0
    #2
    use $matches[0][0] not [1][0]

    if in doubt use print_r($matches); to see what is stored in the array.
     
    plussy, Sep 21, 2012 IP