Display recent posts as thumbnails in sidebar in WordPress 2.9

April 28, 2010 · Print This Article

Starting with WordPress 2.9 is no longer need to use custom fields and hacks to have thumbnails in your wordpress articles or even on widgets area, sidebars, footers etc.

 

For instance, to make a thumbnails area for random latest 10 recent posts, use the following code:

 

<?php
$my_query = new WP_Query('showposts=10&orderby=rand');
if( $my_query->have_posts() ) {
echo '<h1>Random Articles</h1>';
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<?php
$attachments = get_posts( array(
'post_type' => 'attachment',
'number_posts' => 1,
'post_status' => null,
'post_parent' => $my_query->post->ID,
) );
if ($attachments) {
?>
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
<?php
$thumbnail_id = $attachments[0]->ID;
echo wp_get_attachment_image( $thumbnail_id );
}
endwhile;
}
wp_reset_query();
?></a>
<?php endif; ?>

You need to keep in mind the thumbnails will have the sizes from your function.php call action settings, and that will not look ok in your sidebar. You can use a CSS style to make them to look how you wish. Example:

.attachment-thumbnail {
height:50px;
width:50px;
padding:5px;
background:#fff;
margin:5px 5px 0 0;
}

Your choice for site templates and wordpress themes

Comments

Got something to say?

You must be logged in to post a comment.