WordPress attachments not displaying when fetching posts with PHP

I’m working on a WordPress site and trying to pull all blog posts using PHP code. I want to display each post with its title, date, excerpt, and any attached files. However, I’m running into an issue where the attachments won’t show up properly.

Here’s my current code:

global $current_post;
$parameters = array(
    'numberposts' => 10,
    'post_status' => 'publish',
    'orderby' => 'date',
    'order' => 'ASC'
);

$blog_posts = get_posts($parameters);
if($blog_posts) {
    foreach($blog_posts as $current_post) {
        setup_postdata($current_post);
        echo '<div class="post-item">';
        echo '<h3>' . get_the_title() . '</h3>';
        echo '<span>' . get_the_date() . '</span>';
        echo '<div>' . get_the_excerpt() . '</div>';
        the_attachment_link($current_post->ID, false);
        echo '</div>';
    }
    wp_reset_postdata();
}

The problem is that while the post titles, dates, and excerpts display correctly, the attachments either don’t show up at all or display “Missing Attachment” text. I need all posts to appear regardless of whether they have attachments or not. What’s the right way to handle this situation?

You’re using the_attachment_link() wrong. That function only works on attachment pages, not for grabbing media from posts. You need to query attachments separately with get_children() or get_posts() using the parent parameter. Here’s what worked for me:

$attachments = get_posts(array(
    'post_type' => 'attachment',
    'post_parent' => $current_post->ID,
    'numberposts' => -1
));

if($attachments) {
    foreach($attachments as $attachment) {
        echo wp_get_attachment_link($attachment->ID);
    }
}

This checks for attachments first, so you won’t get that “Missing Attachment” text on posts without media files.

hey, it looks like you’re using the_attachment_link() which is meant for attachment posts. try using get_attached_media() to get the files linked to your posts, and then loop through them to display properly.

WordPress treats media attachments and post content differently. When you upload files through the media library and insert them into posts, they’re stored as separate attachment records in the database with a parent-child relationship to the post.

I hit this exact problem last year building a document portal. The best solution was using get_attached_media() - it’s built specifically for this:

$media = get_attached_media('', $current_post->ID);
if(!empty($media)) {
    foreach($media as $attachment) {
        echo '<a href="' + wp_get_attachment_url($attachment->ID) + '">' + $attachment->post_title + '</a>';
    }
}

This fixes the “Missing Attachment” issue because it only shows links when attachments actually exist. Leave the first parameter empty in get_attached_media() to grab all media types, or specify ‘image’, ‘video’, etc. to filter by type.