Last Updated: September 09, 2019
·
3.234K
· espidesigns

Wordpress Featured Image to Post Attachment to Default Thumbnail Fallback

The code below is a 3-level fallback technique for WP image thumbnails. This code first loads the featured image if it's assigned to the post. If it is not set, the code will look for the first image attached to the post. Finally if there is no image associated with the post, a default 'no image' photo will be loaded, which should have been created and uploaded beforehand.

/* Function to process your thumbnail & image 
   Copy and paste the code below to your functions.php */

function get_attachment_picture(){
    global $post, $posts;
    $image_id = get_post_thumbnail_id();  //read featured image data for image url
    $attached_to_post = wp_get_attachment_image_src( $image_id, 'blog-grid' );
    $related_thumbnail =  $attached_to_post[0];                         

    if($related_thumbnail == ""):
        $attachments = get_children( array(
            'post_parent'    => get_the_ID(),
            'post_type'      => 'attachment',
            'numberposts'    => 1, 
            'post_status'    => 'inherit',
            'post_mime_type' => 'image',
            'order'          => 'ASC',
            'orderby'        => 'menu_order ASC'
            ) );
        if(!empty($attachments)):                                                   //check if there's an image attached or not
            foreach ( $attachments as $attachment_id => $attachment ) {
              if(wp_get_attachment_image($attachment_id) != ""):
                  $related_thumbnail = wp_get_attachment_url( $attachment_id );
              endif;                        
            }
        else:                                                                       // if no attachment 
            $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)):
                $related_thumbnail = $first_img;
            else:
                $related_thumbnail = bloginfo('template_directory')."/images/no-image.jpg";    //define default thumbnail, you can use full url here.
            endif;
        endif;   
    endif;  

    echo $related_thumbnail;
}   

The code above returns only an image URL. Call it as an image src attribute like below. For image resizing, a third-party resizing script is needed, like thumb.php or timthumb.php.

Copy and paste the code below in your template page like index.php, archive.php, single.php, etc.

<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><img src="<?php bloginfo('template_directory'); ?>/functions/thumb.php?src=<?php get_attachment_picture();?>&amp;h=300&amp;w=400&amp;zc=1" alt="<?php the_title_attribute(); ?>" class="attachment featured-image alignleft"></a>    <!-- with image resizing -->

6 Responses
Add your response

i ve tried this in my WordPress theme and it's not working or may be i didn't place it well. can you help me out please?

over 1 year ago ·

@cyberwebkit, do you have the timthumbs script or the no-image.jpg in the right place?

over 1 year ago ·

yes i do.

over 1 year ago ·

my theme has 4 loop.php and 1 index, so am confused.

over 1 year ago ·

what theme are you using? hit me up on skype: espidesigns

over 1 year ago ·

Tbanks for your sharing about this practice. In fact, for me, I don't prefer to modify the coding thing, but resort to the WordPress plugin to achieve my goal an easy way. I finally opt Default Featured Image plugin after reading https://wpmatter.com/how-to-set-default-fallback-image-wordpress/. Hope this one can be added into your sharing.

over 1 year ago ·