I want to get the first image URL of a post, in this order: first get the featured image of the post, if not, get the first image inserted on the post, if not, use the default image.

At the moment I’m using this code:

    function get_first_image() {
        global $post, $posts;
        //First get the featured image
        if (has_post_thumbnail($post->ID)) {
            $first_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID));
            echo $first_image;
        } else {
            //If not, get the first image
            $first_img = '';
            $output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches);
            $first_img = $matches[1][0]; //LINE 470
            //If the variable is empty, use the default image
            if(empty($first_img)) {
                $first_img = ot_get_option('szt_featuredimage');
            return $first_img;

It works partially. It returns the featured image and the first image of the post, but it doesn’t work perfect getting the default image:

Notice: Undefined offset: 0 in
/var/www/Seozeta/wp-content/themes/seozeta/functions.php on
line 470
[…] /wp-content/uploads/2014/04/default-image.png

What can I do to fix this Notice?

EDIT: Ok, I think I already fixed it. I just replaced this piece of code:

        $output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches);
        $first_img = $matches[1][0];

for this:

            if ( $output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches) ) {
                $first_img = $matches[1][0];

Read more here: Get the first image URL of a post, by order (featured, first image, then default)


If you know the solution of this issue, please leave us a reply in Comment section, to update the question.

Related Wordpress search:

, , , , ,

Wordpress related questions and answers: