Site icon Hip-Hop Website Design and Development

How can I batch delete all unattached images with WP-CLI or other automated process?

After using WPML Media, a plugin that creates duplicates of each image for each language, we now have almost 100,000 duplicate images that we’re not going to use and need to get rid of.

We need to not only delete these from the filesystem itself, but also need to make sure that deleting all references in the database as would typically happen if one were to manually delete them through the media gallery.

I’m looking for a WP-CLI solution, if it’s possible. This solution was very helpful, but it does all images, not just those that are unattached / unused within the system.

How can I bulk delete media and attachments using WP-CLI?

Given another solution, the OP put in the comments that he achieved his solution ultimately with SQL.

How do I delete thousands of unattached images?

I’m no stranger to the command line or mysql, but am not familiar enough with WP tables to create a query to maintain the integrity of the database. If you are, then please suggest a pure database related solution, or PHP script that would hook into the system and do things the “wordpress” way.

I am not looking for a plugin based solution. I have tried DNUI, DX Delete Attached Media, and a score of others that all ended badly.

UPDATE:
Using “parent=0” to determine if an image is attached or not was a very clever solution, and I marked it as the answer.

There is a way to legitimately use an image in a post and the parent still equals 0; that’s when you visit the image details in the media library, and you copy the full image source URL to be manually pasted into a post. The accepted answer’s solution will delete these as well. Because of that, I would like to encourage other solutions too that would take this into consideration.

That would perhaps require scanning the database to find instances of the image name, perhaps similar to the algorithm wp-cli search-replace would use?