Popular Categories

How to get featured images outside loop in WordPress?

This is a very common requirement that we need to display the post image. The way to do this outside the loop is to use the following snippet:

$post_id = 123; // use your post id
$thumb_id = get_post_thumbnail_id($post_id);
$thumb_url_array = wp_get_attachment_image_src($thumb_id, ‘full’, true);
$thumb_url = $thumb_url_array[0]; //this gets you the url of the image

Within the loop its simple, just modify the above code a bit and use:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<h2><?php the_title() ;?></h2>
<?php the_excerpt();

$thumb_id = get_post_thumbnail_id();
$thumb_url_array = wp_get_attachment_image_src($thumb_id, ‘full’, true);
$thumb_url = $thumb_url_array[0]; //this gets you the url of the image

endwhile; else: ?>

<p>Sorry, no posts to list</p>

<?php endif; ?>