1

How can I obtain ID of images attached (and not necessarily inserted) to a custom post type ? I want to pass this argument in order to use this images in soliloquy slider

1
  • 2
    Please take the time to read How to Ask.
    – kaiser
    Commented Sep 17, 2014 at 20:37

2 Answers 2

1

Use this function get_attached_media

$images = get_attached_media( 'image' );

You can also pass as a second parameter the ID of a post.

This function returns and array of Post object, the ID is in the ID property.

1

You can get the array of Image ID by using this function

if (!function_exists('get_associated_media')) {

    function get_associated_media($post_id) {
        $attachmentIds = array();
        $media = get_children(array(
            'post_type' => 'attachment',
            'post_parent' => $post_id,
            'post_status' => 'inherit',
            'post_mime_type' => array('image/jpeg', 'image/gif', 'image/png'),
            'numberposts' => -1
        ));

        foreach ($media as $file) {
            $attachmentIds[] = $file->ID;
        }
        $attachmentIds[] = get_post_thumbnail_id($post_id);
        return array_unique($attachmentIds);
    }
}

This code goes in function.php file of your active child theme (or theme) or also in any plugin file.

The code is tested and fully functional.

USAGE: You have to pass the Post ID in this function and you will get the images ids.


Reference:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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