WP-CLI » Delete unused images in WordPress using WP CLI

Delete unused images in WordPress using WP CLI

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?

Leave a Comment

I enjoy constructive responses and professional comments to my posts, and invite anyone to comment or link to my site.

Recommended