Wordpress - How can I batch delete all unattached images with WP-CLI or other automated process?
You can try this (untested) modification to the answer you linked to by @something
wp post delete $(wp post list --post_type='attachment' --format=ids --post_parent=0)
to delete attachments without parents.
To target a given mime type
, e.g. image/jpeg
try:
wp post delete $(wp post list --post_type='attachment' \
--format=ids --post_parent=0 --post_mime_type='image/jpeg')
Notes:
Remember to backup first before testing!
Unattached images might still be used in the post content or e.g. in widgets.
The accepted answer will not delete unattached media for attachments where the parent doesn't exist anymore... this could happen when parents are deleted via the db or some other process that doesn't mark the attached media parents as 0.
Here is a cli command that will do that check.
wp post delete $(wp db query --skip-column-names --batch "select DISTINCT p1.ID from wp_posts p1
left join wp_posts p2 ON p1.post_parent = p2.ID
where p1.post_type = 'attachment'
AND p2.ID is NULL") --force