WordPress: Get attachments

As of WordPress V3.3 there’s still no direct WordPress function to retrieve attachments of a given page or post. There are functions to retrieve attachment related info such as URL and source, given that you know that ID of the attachment.

List of attachment of IDs of a given page or post can be retrieved via get_children().

This is one of the essential functions that I always add to functions.php:

// by default gets attached images from current post
function get_attached_images($id = null) {
    global $post;
    if (is_null($id)) $id = $post->ID;
    return get_children(array(
        'post_parent' => $id,
        'post_type' => 'attachment',
        'post_status' => 'inherit',
        'post_mime_type' => 'image', // use 'video' for videos
    ));
}

To display list of attached images for current post:

foreach (get_attached_images() as $image) {
    echo wp_get_attachement_image($image->ID);
}

Check function reference for wp_get_attachment_image() and more attachment related functions that comes with WordPress.

Note: this function is probably not required if images have been inserted as part of the content.

Leave a Reply

Your email address will not be published. Required fields are marked *