Post Pic

How to show WordPress 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

Jul 30 2011 21:14

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?

Sep 06 2011 21:22

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>

Sep 15 2011 05:45

This works on ly on posts but how do you get attachments of a certain custom post type? Anyone?

Sep 15 2011 10:19

Thanks Stephen
I will definitely try it
thanks for your help

Nov 13 2011 12:20

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!

Dec 31 2011 07:03

@Dino, i also want the solution

Jan 07 2012 00:40

@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:

Leave a Comment

* Name, Email, Comment are Required