Skip to content
Advertisement

Get first image from last post in WordPress

Can’t get the first picture in the last post (function – get_first_post_image). Where is the mistake? Please help me. Thank you in advance for your help.

function get_first_post_image() {
    global $post, $posts;
    $first_img = '';

    ob_start();
    ob_end_clean();

    if(preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches)){
        $first_img = $matches [1] [0];
        return $first_img;
    }
    else {
        $first_img = "http://yyyyyy/post-default.png";
        return $first_img;
    }
};
    
function custom_function(){
    $args = array( 
        'numberposts' => '1', 
    );

    $recent_posts = wp_get_recent_posts( $args );

    foreach( $recent_posts as $recent ):
        $post_id        = $recent['ID'];
        $post_url       = get_permalink($recent['ID']);
        $post_title     = $recent['post_title'];
        $post_content   = $recent['post_content'];
        $post_thumbnail = get_the_post_thumbnail($recent['ID']);
        $imglink        = get_first_post_image($recent['ID']);
    endforeach;
    
    $data = '... ' . $imglink . ' ...';
    
    ....
    
}

Sorry for my bad English.

Advertisement

Answer

I’ve rewritten the function to return the default image if no first image is found. Best way of parsing HTML is DOM parsing, not regex.

function get_first_post_image(string $post_content): string
{
    $defaultImage = 'http://yyyyyy/post-default.png';

    libxml_use_internal_errors(true);
    $doc = new DOMDocument();
    $doc->loadHTML($post_content);

    $img = $doc->getElementsByTagName('img');
    if (!$img->length) return $defaultImage;

    return $img->item(0)->getAttribute('src') ?: $defaultImage;
}

You are calling get_first_post_image() with the ID instead of the post content.

change

$imglink = get_first_post_image($recent['ID']);

to

$imglink = get_first_post_image($recent['post_content']);

I’ve updated the function above

  • Changed Signature
  • Removed global $post
  • Changed loadHtml()
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement