WordPress Get 1 attachment per post from X category outside the loop
Posted
by davebowker
on Stack Overflow
See other posts from Stack Overflow
or by davebowker
Published on 2010-05-29T19:47:56Z
Indexed on
2010/05/29
19:52 UTC
Read the original article
Hit count: 283
Hey,
Hope someone can help with this. What I want is to display 5 attachments but only 1 attachment from each post from a specific category in the sidebar, which links to the posts permalink.
I'm using the following code so far which gets all attachments from all posts, but some posts have more than 1 attachment and I just want to show the first one, and link it to the permalink of the post.
So although the limit is 5 posts, if one post has 4 attachments then currently it will show 4 from one, and 1 from the other totalling 5, when what I want it to do is just show 1 from each of 5 different posts.
<?php
$args = array(
'post_type' => 'attachment',
'numberposts' => 5,
'post_status' => null,
'post_parent' => null, // any parent
'category_name' => 'work',
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $post) {
setup_postdata($post);
the_title();
the_permalink();
the_attachment_link($post->ID, false);
the_excerpt();
}
}
?>
Cheers. Dave
© Stack Overflow or respective owner