Listing Attached Files

You can display all the attached files of a post without going to the trouble of inserting each one into the post content. The required code looks very much like a second Loop, as shown in Listing 7-6. This could be placed inside the main Loop, perhaps just after the_content().

Listing 7-6. Listing a post's attached files inside the Loop

$attachments = get_children(array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => $post->ID ));

<ul class="attachments"> <?php foreach ($attachments as $attachment) {

if (substr($attachment->post_mime_type, 0, 5) != 'image') {

$type = str_replace('/', '-', $attachment->post_mime_type); echo "<li class='$type'>"; the_attachment_link($attachment->ID, false); echo '</li>';

The get_children() function can also be used to display child pages, but here you've used the post_type argument to limit the list to attachments. Setting the numberposts argument to -1 ensures that you get all attachments, and the post_parent argument is set to the current post's ID so that you get only those attachments that were uploaded to this particular post.

As you loop through the returned attachment objects, you need to skip over the images, since those will work better with the [gallery] shortcode shown in Chapter 4. (You could use a similar if() statement to exclude any other type of file.) For the rest of the attached files, you need to clean up the MIME type a little bit for use with CSS. You use the attachment's MIME type as the list item class, which allows you to style each link with a file icon background image. In order to get a valid class name, however, you replace the slash in the original MIME type (e.g. application/pdf) with a dash using PHP's str_replace() function.

You separate the_attachment_link() instead of placing it in the echo statement because it echoes by default.

Listing 7-7 provides a few examples of the CSS you might use to style the attachment links, assuming a 16-pixel icon such as FamFamFam's free Mini set (www.famfamfam.com/lab/icons/mini/). The end result is shown in Figure 7-1.

Listing 7-7. CSS for Listing 7-6

ul.attachments li {

list-style: none;

ul.attachments li a {

padding-left: 20px; line-height: I8px; background-position-top: 0; background-position-left: .5em; background-repeat: no-repeat;

background-image: url(img/icons/attachment.gif); /* default */

ul.attachments li.application-pdf a {

background-image: url(img/icons/pdf.gif);

ul.attachments li.application-zip a {

background-image: url(img/icons/zip.gif); }_

One comment

A post with a single comment

Appi I cation Form Q Package soiled o-l 2007 <3\ 13:2^ J-TI ■ 1_ . ; ..y n . heat

Figure 7-1. The styled list of post attachments

0 0

Post a comment