
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.
14 Responses
I don’t quite understand this? Where do you specify attachments? There isn’t anywhere when posting to specify attachments. Are you just talking about when you use the media upload?
That’s interesting… didn’t know about attachments
Attachments are simply any files you upload to a post using the media buttons
Cool! this is all that I need. Many Thanks.
i wish you could specific a category to show only attachments from that category…….
you could, if i got time later on, i’ll post some updated code to do so …
voila,
just ad ‘in_category’ around the function to filter category.
‘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);
}
}
}
?>
‘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);
}
}
}
?>
can’t pus code in the comments (or i just don’t know how).
so here, just add that if ( in_category( ‘about’ )) { before, and } after the function…
hope it helps
Is it possible to extract just the first image attached to a post and display that from all my posts? That would leave me with a grid(CSS styled) of images on my blog that when clicked would open each post.
if you want to show only the first atachement try this
[code]
$args = array(
'post_type' => 'attachment',
'numberposts' => null,
'post_status' => null,
'post_parent' => $post->ID
);
$attachments = get_posts($args);
if ($attachments) {
$attachment = $attachments[0];
echo apply_filters('the_title', $attachment->post_title);
the_attachment_link($attachment->ID, false);
}
[/code]
i didn’t test it, but it should work
now if you want to list the fisrt attachement of each post on page, that’s something else ..
hope it helps
Trackbacks: