WordPress.org

Support

Support » Plugins and Hacks » Trouble retrieving the first image in a post

Trouble retrieving the first image in a post

  • memelocker
    Member

    @memelocker

    Iam trying to retrieve the first image in a post and display it on the front page. Ive already place this code in my functions.php
    ive placed

    [Code moderated as per the Forum Rules. Please use the pastebin]

    and then placed <?php echo catch_that_image() ?> in my index.php, but it is still not working. What am i doing wrong?
    Thank you in advance

Viewing 1 replies (of 1 total)
  • memelocker
    Member

    @memelocker

    sorry i didn’t read the rules. The code is

    // 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;
    }

    Also what is the loop?

Viewing 1 replies (of 1 total)
  • The topic ‘Trouble retrieving the first image in a post’ is closed to new replies.