Getting rid of unused product images in WooCommerce with WP-CLI and Bash

I recently worked on a WordPress theme-based website with over 1,600 products, each having around 20 gallery images-adding up to more than 39,000 images. These products were imported from Shopify, and all images were 2000px wide. This made the site balloon to a massive 32 GB, which made backups, migrations, and server space a real challenge. In the end, I managed to cut it down to 15 GB. So, how did I do it?

1. The thought process

Since it’s a theme-based site and knowing how WordPress and WooCommerce work, I noticed that each image creates about 13 different-sized versions, like:

  • public_html/wp-content/uploads/2025/06/92b92a69.jpg (original)
  • public_html/wp-content/uploads/2025/06/92b92a69-100×100.jpg
  • public_html/wp-content/uploads/2025/06/92b92a69-1300×866.jpg
  • public_html/wp-content/uploads/2025/06/92b92a69-500×313.jpg
  • public_html/wp-content/uploads/2025/06/92b92a69-1000×667.jpg
  • public_html/wp-content/uploads/2025/06/92b92a69-600×400.jpg
  • public_html/wp-content/uploads/2025/06/92b92a69-340×227.jpg
  • public_html/wp-content/uploads/2025/06/92b92a69-700×700.jpg
  • public_html/wp-content/uploads/2025/06/92b92a69-960×640.jpg
  • public_html/wp-content/uploads/2025/06/92b92a69-230×90.jpg
  • public_html/wp-content/uploads/2025/06/92b92a69-1536×1024.jpg
  • public_html/wp-content/uploads/2025/06/92b92a69-46×46.jpg
  • public_html/wp-content/uploads/2025/06/92b92a69-120×120.jpg
  • public_html/wp-content/uploads/2025/06/92b92a69-48×48.jpg

It turned out there were over 500,000 images. That made me wonder: what image sizes are really used across the site? So I checked everywhere:

Frontend:

  • Product listings (homepage snippets, shop page, related products)
  • Product galleries
  • The e-commerce flow: side cart, pop-ups, cart, checkout, purchase page, WooCommerce emails

Backend:

  • Media library including gallery thumbnails
  • Products list page
  • Product edit page (main image, gallery, variation images)
  • I also went to Settings > Media and set medium and large image sizes to the same 500×313, which helped remove another image variation.

In the end, the site only used these sizes:

  • 100×100
  • 340×227
  • 500×313
  • 700×700
  • 960×640
  • 1000×667

With that info, the plan was clear: remove unused images and shrink the main ones.

2. Custom WP-CLI scripts for removing and optimizing images

The goal was clear, but how to do it properly? I didn’t want to use any plugins because:
a) most plugins actually create even more files
b) finding the right plugin would take time, and it probably wouldn’t do exactly what I needed

So, I turned to my trusty pal ChatGPT, and together we wrote two scripts.

Note: Make sure to back up your /wp-content/uploads/ folder before you start applying the to your website!

2.1 Script 1: Remove all unused images by criteria

The good thing in my case was that all images were JPGs stored in “/wp-content/uploads/2025/06/”. This made it easy to focus only on that folder and work with the images inside.

# Replace the directory and file format according to your needs 
# Example: find wp-content/uploads/ -regextype posix-extended -type f \( -name '*.jpg' -o -name '*.png' \) \
find wp-content/uploads/2025/06/ -regextype posix-extended -type f -name '*.jpg' \
  # This include all images with a size in their name (e.g. "-46x46.jpg")
  -regex '.*-[0-9]+x[0-9]+\.jpg$' \
  # This exclude the any image that matches the provided structure
  # Important to specify only the width because sometimes there is variation in the height size
  ! -regex '.*-500x[0-9]+\.jpg$' \
  ! -regex '.*-700x[0-9]+\.jpg$' \
  ! -regex '.*-1000x[0-9]+\.jpg$' \
  ! -regex '.*-960x[0-9]+\.jpg$' \
  ! -regex '.*-100x[0-9]+\.jpg$' \
  ! -regex '.*-340x[0-9]+\.jpg$' \
  # Make sure to test the script before running the "-delete" command. 
  # Just replace "-delete" with "-print". 
  # "-print" will list all the files that will be affected.
  -delete

NB!: Test your script first by replacing -delete with -print.

What the script does:

  • Targets .jpg files in wp-content/uploads/2025/06/
  • Deletes all WordPress-generated thumbnails except for specific sizes

2.2. Script 2: Resize all primary images and optimize them

I wanted to get the most out of this optimization, so I decided to reduce the image size since most were huge (around 2000px in width), and that was more than the site actually needed. At first, I planned to shrink them to 1000px, but the site has a zoom-on-hover feature that lets users see product details up close. To keep the image quality high enough for that, I settled on 1400px, which turned out to be the perfect balance.

On top of that, I used an ImageMagick script to further optimize the images by slightly adjusting quality without affecting how they look and removing all metadata.

#!/bin/bash

# Gets all optimized images - all posts with type 'attachment' (filtering image files) marked as 'optimized'
OPTIMIZED_IDS=$(wp db query "SELECT pm.post_id FROM wp_postmeta pm JOIN wp_posts p ON pm.post_id = p.ID WHERE pm.meta_key = '_optimized' AND pm.meta_value = '1' AND p.post_type = 'attachment';" --skip-column-names)

# Creates a map (associative array) for quick O(1) lookup of all image IDs
declare -A optimized_map
while read -r id; do
  optimized_map["$id"]=1
done <<< "$OPTIMIZED_IDS"

wp post list --post_type=attachment --post_mime_type=image/jpeg --format=csv --fields=ID,guid \
# Choose the directory and file exclusions you want to make 
# Here, I look in /wp-content/uploads/2025/06/ and exclude any size suffixes in filenames (e.g. "-46x46.jpg")
| awk -F, '$2 ~ /\/uploads\/2025\/06\// && $2 !~ /-[0-9]+x[0-9]+\.jpg$/' \
| while IFS=, read -r ID URL; do

  # Ensures already optimized images are skipped and lists their names in the terminal
  if [[ ${optimized_map[$ID]} ]]; then
    echo "✅ Already optimized: $URL"
    continue
  fi

  RELATIVE_PATH="${URL#*wp-content/}"
  LOCAL_PATH="./wp-content/${RELATIVE_PATH}"

  # Checks if the file exists
  if [ ! -f "$LOCAL_PATH" ]; then
    echo "⚠️ File not found: $LOCAL_PATH"
    continue
  fi
  WIDTH=$(identify -format "%w" "$LOCAL_PATH")

  # Checks if the file's width is above 1400px and resizes it if so 
  # Comment out the convert line the first time you run this script to see which files will be optimized
  if [ "$WIDTH" -gt 1400 ]; then
    echo "🔧 Resizing: $LOCAL_PATH (Width: $WIDTH)"
    convert "$LOCAL_PATH" -resize 1400x "$LOCAL_PATH"
  fi

  # Optimizes the image by stripping all metadata and adjusting image quality 
  # You can adjust the quality number for more compression, but don’t go below 80 to avoid noticeable quality loss 
  # Comment out the convert line the first time you run this script to see which files will be optimized 
  echo "🗜 Optimizing: $LOCAL_PATH"
  convert "$LOCAL_PATH" -strip -interlace Plane -quality 90 "$LOCAL_PATH"

  # Adds post meta to the image so it won't be re-optimized next time you run the script 
  # Comment this out if you’re running the script as a test and have already commented the two convert lines above
  wp post meta update "$ID" _optimized 1

done

NB!: Make sure to test your script first by commenting out the following lines:

# convert "$LOCAL_PATH" -resize 1400x "$LOCAL_PATH"
# convert "$LOCAL_PATH" -strip -interlace Plane -quality 90 "$LOCAL_PATH"
# wp post meta update "$ID" _optimized 1

What does the script do?:

  • Retrieves all already optimized images by querying the database for attachment posts with the _optimized = 1 meta key and stores their IDs.
  • Stores these IDs in a map (associative array) for fast lookup.
  • Filters only the original images, excluding resized versions (e.g., -100×100.jpg).
  • Process each image:
    • Skips already optimized files
    • Skips missing files with a warning
    • Resizes images if width > 1400px
    • Optimizes them using ImageMagick:
      • Strips metadata
      • Sets quality to 90
      • Enables progressive rendering
    • Tags the image post with _optimized = 1 so it’s skipped next time the script runs

2.3. How to run all this?

I stuck with the KISS approach – a simple solution that gets the job done and can be rerun anytime I need. So, I put the scripts into two separate .sh files.

For running the scripts, I chose the simplest way possible – I used my hosting’s cPanel terminal instead of SSH. It turned out WP-CLI and ImageMagick weren’t installed on the server, so I had to install them first.

After that, I just navigated to the website’s root directory (in my case, public_html) and bashed the scripts.

3. Conclusion

These scripts help you maintain a lean uploads folder by:

  • Deleting redundant thumbnails
  • Resizing overly large originals
  • Optimizing image files

Ideally, this could be turned into a great plugin and further optimized, but I chose to keep it simple and focus on getting results for now.