
Since WordPress 2.5, attachments management in WordPress have been improved and is now very powerful. Today, I’m going to show you a simple code snippet that you can use in your WordPress theme to display post attachments.

Since WordPress 2.5, attachments management in WordPress have been improved and is now very powerful. Today, I’m going to show you a simple code snippet that you can use in your WordPress theme to display post attachments.
To achieve this recipe, just paste the following code anywhere in your post.php file and attachments will be displayed.
$args = array(
'post_type' => 'attachment',
'numberposts' => null,
'post_status' => null,
'post_parent' => $post->ID
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) {
echo apply_filters('the_title', $attachment->post_title);
the_attachment_link($attachment->ID, false);
}
}
Credit : Snipplr.
7 Responses
Great snippet! thanks
is there a way to orgenize all the attachment in a list (ul)?
and show it on a sidebar?
I want to show each post’s specific attachments (in my case – PDF’s) on the sidebar.
any suggestions?
Very useful post!
Gil, to organize them in a list, just wrap the entire block in <ul>
</ul> tags (outside the php block), then wrap each iteration through the
loop in <li></li> tags.
<ul>
<?php
$args = array(
‘post_type’ => ‘attachment’,
‘numberposts’ => null,
‘post_status’ => null,
‘post_parent’ => $post->ID
);
$attachments = get_posts($args);
if ($attachments) {
foreach($attachments as $attachment){
echo "<li>";
echo apply_filters(‘the_title’, $attachment->post_title);
the_attachment_link($attachment->ID, false);
echo "</li>";
}
}
?>
</ul>
This works on ly on posts but how do you get attachments of a certain custom post type? Anyone?
Thanks Stephen
I will definitely try it
thanks for your help
How would I combine this with a custom WP query? I want it to pull images from a page..
the query earlier on..
$bd_clients = new WP_Query(‘pagename=clients’);
loop..
have_posts()) : $browndog_clients->the_post(); ?>
Many thanks!
@Dino, i also want the solution
@Dino and @AliHussain
I’m no expert, but I think the code should work because that it looks into the current post, but if you still need the code to do what you want you could mail me at neville (at) nevi (dot) me, and I’ll write a snippet for you.
Trackbacks: