Hello Friends,WordPress offers lots of great features and featured image for a post or page is one of great feature to add image to post or page easily.In this article I am going to explain how you can show the list of featured images from top 5 latest posts. One of my client need to show featured images from latest posts in header of his site So I thought to share it on my site So it can be helpful for anyone.
So First we will fetch latest 5 posts then use loop and then get featured image for each post and then show it. So below is code to achieve it :
<div id="header_right"> <?php query_posts('showposts=5'); ?> <?php while (have_posts()): the_post(); ?> <?php if (has_post_thumbnail( $post->ID ) ): ?> <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' ); ?> <a href="<?<span class=">php echo get_permalink(); ?>"><img alt="" src="<?php echo $image; ?>" /></a> <?php endif; ?> <?php endwhile; wp_reset_query(); ?> </div>
Above code will show 5 featured images from latest 5 posts. In above code line number 2 used to query latest 5 posts and then we simply start while loop to go through each posts. In 4th line we checked that current post have featured image attached or not? If post will not have featured image then it will skip featured image for this post and then check for next post. In 5th line we are using ‘wp_get_attachment_image_src’ wordpress function to get featured image link or url. You can pass ‘thumbnail’,’large’,’full’ instead of ‘medium’. For more information check ‘wp_get_attachment_image_src‘.Next in 6th line we simple each image url in image tag. In 7th and 8th line end if and end while loop. Line number 9 is important to reset the loop because we customize parameters.
So in this way we can make a section in WordPress to show featured images from latest posts. I hope this posts will help someone. If you have any questions regarding this or want any help regarding this you can post in comment.