Show All Media Attachments to a Post

[ad_1]

Prior to WordPress 3.6, we had to run a query to retrieve all media attachments to a specific post. We had to do something like this.

// show all WordPress post attachments
$args = array(
  'post_type' => 'attachment',
  'posts_per_page' => -1,
  'post_status' => 'any',
  'post_parent' => $post->ID
);
$attachments = get_posts( $args );
if ( $attachments ) {
    foreach ( $attachments as $attachment ) {
        echo apply_filters( 'the_title', $attachment->post_title );
        the_attachment_link( $attachment->ID, false );
    }
}

But WordPress 3.6 made it really simple for us. WordPress 3.6 introduced the new get_attached_media() function that makes it very easy to retrieve any type media attachments to a specific post. So now we call this function to get all attached media, regardless of mimetype.

// show all WordPress post attachments
$attachments = get_attached_media( '', $post->ID );
if ( $attachments ) {
    foreach ( $attachments as $attachment ) {
        echo apply_filters( 'the_title', $attachment->post_title );
        the_attachment_link( $attachment->ID, false );
    }
}
[ad_2]

Leave a Reply

Random Post Selection ::

Recent Posts

Unlock Unlimited Downloads