I haven't tested this but logically... ;)
Images attached to posts should have post_parent
greater than zero, with the most recent posts (post parents) having the highest ID, though longstanding draft posts might throw this off a bit. So, if you order by the post_parent
descending you should have the top 12 attachments associated with your posts.
$args = array(
'post_type' => 'attachment',
'posts_per_page' => 12, // numberposts is long since deprecated in WP_Query
'post_status' => inherit,
'orderby' => 'post_parent',
'order' => 'DESC'
);
Now, if you are getting attachments from pages and CPTs you will need a more complicated solution and will have to query your posts for IDs,then pull attachments.
Any idea how to get the link of the parent post/page? I tried
"get_permalink( $post->post_parent )" but it gives me only the latest
post. (From a comment below)
The way your code is written, the $post
global isn't going to be set. What you need is $attachment->post_parent
. Or, my preference, skip the get_posts()
wrapper and use WP_Query
itself:
$args = array(
'post_type' => 'attachment',
'posts_per_page' => 12, // numberposts is long since deprecated in WP_Query
'post_status' => 'inherit',
'orderby' => 'post_parent',
'order' => 'DESC'
);
$attachments = new WP_Query( $args );
if ( $attachments->have_posts() ) {
while ( $attachments->have_posts() ) {
$attachments->the_post();
var_dump($post->post_parent); // now it is set
echo '<li>';
echo wp_get_attachment_image( $post->ID, array('90', '90') );
echo '</li>';
}
}