0

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>';
}
1

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>';
}

?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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