Dalton Russell
Dalton Russell

Reputation: 101

How to get all attachments for a wordpress post?

I am currently attempting to get all the attachments that are attached to each individual post on WordPress and allow a user to download the attachments.

I have looked into the get_attached_media() function in WordPress but I am not sure how to make the files downloadable once I get the media.

Upvotes: 6

Views: 20026

Answers (2)

Sebas Rossi
Sebas Rossi

Reputation: 39

Please note that the post_parent field DOES NOT retrieve attachments of the post in all cases. This value is filled on the database ONLY if the image is loaded and attached at the same time (on the post/page editor) But it's value will be 0 zero if image has been previously added to the library.

post_parent just means the image was initially uploaded for this particular post (as opposed to uploading via Media Library screen),

https://core.trac.wordpress.org/ticket/30691

Upvotes: 0

Bhumi Patel
Bhumi Patel

Reputation: 589

Try this code this may help you:

With below code you can fetch all type of media attachment if you need particular media type then you can add one more args 'post_mime_type' => 'image'

<?php if ( $post->post_type == 'post' && $post->post_status == 'publish' ) {
        $attachments = get_posts( array(
            'post_type' => 'attachment',
            'posts_per_page' => -1,
            'post_parent' => $post->ID,
            'exclude'     => get_post_thumbnail_id()
        ) );

                if ( $attachments ) {
                    foreach ( $attachments as $attachment ) {
                        $class = "post-attachment mime-" . sanitize_title( $attachment->post_mime_type );
                        $thumbimg = wp_get_attachment_link( $attachment->ID, 'thumbnail-size', true );
                        echo '<li class="' . $class . ' data-design-thumbnail">' . $thumbimg . '</li>';
                    }

                }
            }
        ?>

Another way you can achieve this:

$media = get_attached_media('image', get_the_ID()); // Get image attachment(s) to the current Post
print_r($media);

Upvotes: 13

Related Questions