This small script uses a for loop to delete one post ID at a time, it will go through the database and list all media files uploaded in the provided data range that are not used inside posts.
Change the date range according to your needs.
for id in $(wp db query "SELECT ID FROM wp_posts WHERE post_date>='2022-10-01' AND post_date<='2022-10-30' AND post_type='attachment' AND post_parent=0" --silent --skip-column-names)
do
wp post delete --force $id
done
Was this post helpful?
Let me know if you liked the post. That’s the only way I can improve. 🙂
Stefan. Good post. We did something similar but it couldn’t cover all use cases like builders. So went and built a plugin to deal with it.
Please check this out: https://wordpress.org/plugins/media-hygiene/
I would love to get your feedback.