WordPress.org

Ready to get started?Download WordPress

Forums

Trouble retrieving the first image in a post (2 posts)

  1. memelocker
    Member
    Posted 2 years ago #

    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

  2. memelocker
    Member
    Posted 2 years ago #

    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?

Topic Closed

This topic has been closed to new replies.

About this Topic