Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm a bit fresh to wordpress theme development (and PHP in general), and I'm curious if there is a way to query XX number of recent images, likely spanning across multiple posts. Basically I want to create a widget that shows a 3x3 set of the most recent images used in posts.

Any thoughts on how one would accomplish this?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

You can use get_posts or create a new WP_Query using the following args (or something similar).

<?php 
$args = array(
   'post_type'      => 'attachment', // attachment post type
   'post_status'    => 'inherit', // all attachments have this post status
   'post_mime_type' => 'image', // make sure you get images only
   'posts_per_page' => 5 // however many images you want
);

When looping through the images, you can use wp_get_attachment_image or wp_get_attachment_image_src to grab the image HTML or image URL respectively.

<?php
$attachments = get_posts($args); // args from above
foreach($attachments as $a)
{
   // replace `thumbnail` with an appropriate image size
   echo wp_get_attachment_image($a->ID, 'thumbnail');
}

You'll also want to read up the widgets API for creating widget. The codex has a basic example. There's also quite a few tutorials out there, here's one I wrote.

share|improve this answer
1  
I don't know why I didn't know this. I had another query virtually identical elsewhere, but where I specified "'post_parent' => $post->ID);" to filter it down to the given post –  James Aug 19 '12 at 13:53
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.