Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm using the code below to first grab the post's attachments (if they're either a Word doc or pdf file), then echoing the url of said attachment. This works great on the first post on a page. However, on each subsequent post the same attachment url is echoed, even if that post doesn't have an attachment. How can I keep that from happening?

$args = array(
                'post_type' => 'attachment',
                'post_mime_type' => array('application/doc','application/pdf'),
                'numberposts' => 1,
                'post_status' => null,
                'post_parent' => $post->ID
            );
$attachments = get_posts( $args );
foreach ($attachments as $attachment) {
    echo '<a href="' . wp_get_attachment_url( $attachment->ID ) . '">Download Spec  Sheet</a>';
    echo '</div>';
}
share|improve this question

1 Answer 1

up vote 1 down vote accepted

Try this:

<?php

if ( $attachments = get_children( array(
        'post_type' => 'attachment',
        'post_mime_type' => array('application/doc','application/pdf'),
        'numberposts' => 1,
        'post_status' => null,
        'post_parent' => $post->ID
)));
foreach ($attachments as $attachment) {
echo '<a href="' . wp_get_attachment_url( $attachment->ID ) . '">Download Spec  Sheet</a>';
echo '</div>';
}

?>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.