21. Mar 2023 |

wp cli to delete unattached images

Yes, I did it. I imported new images with every product import so now I have 15000+ images in my media library.

for id in $(wp db query "SELECT id FROM wp_posts WHERE post_date <= '2023-03-20' AND post_date >= '2023-03-15' AND post_type='attachment' AND post_parent=0 AND post_author NOT IN(1,4)" --skip-column-names); do wp post delete --force $id; done

This is the wp cli command that does the job. I found it here.

Just to see how many images will be deleted you can use following query:

wp db query "SELECT COUNT(id) FROM wp_posts WHERE post_date <= '2023-03-20' AND post_date >= '2023-03-01' AND post_type='attachment' AND post_parent = 0 AND post_author NOT IN (1,4)"

You can modify post_author IDs and date ranges as you like. For testing you can as LIMIT parameter to the query.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.