Script to get a list of all images that are detached?

In my functions.php, I have a need to list all images in the uploads folder which are not currently attached to a post in the WP database.

It appears that every time an image is uploaded to the WP uploads folder (via FTP or via Media Manager), a records gets inserted in the WP database, right?

How can I obtain a list of all images that are not currently attached to any post?

2 Answers
2

This should work:

$args = array(
    'post_type' => 'attachment',
    'numberposts' => -1,
    'post_status' => null,
    'post_parent' => 0
); 
$attachments = get_posts($args);

if ($attachments) {
    foreach ($attachments as $post) {
        setup_postdata($post);
        the_attachment_link($post->ID);
    }
}

Leave a Comment