Turn off auto-generating thumbnails for images

When you upload an image to the WP Media Library, all the "neccessary" thumbnails (of various sizes and scales) are automatically generated, depending on your WP site settings and the theme you are using.

I use reGenerate Thumbnails Advanced to regenerate all of the current images on my site and remove all of the thumbnails. To prevent the generation when you upload new images in the future, you can use the Stop Generating Unnecessary Thumbnails plugin.

Resize and compress the featured images

When you upload an image to the WP Library, this image can be very large (in MB). It's recommended to resize and compress the image before uploading it to your site, but what about the images you have already uploaded?

I use imagemagick to shrink the images to a maximum width and height of 1280x1080 and skip images that are below this value.

Resize all the images in the current folder and put the new images in ./out/

magick mogrify -path out -resize 1280x1080\\> *

In order to compress the images, you can use iloveimg website.

Take all originally featured images from subfolders

If WP Amin > Settings > Media > "Organize my uploads into month- and year-based folders" is enabled (normally this option is enabled by default), every time you upload a new image, it will be placed in a subfolder like 2022/09/21/. So, if you want to find a featured image of a post to resize and compress it, you need to know which folder it belongs to.

Use the following Python script to move all images in subfolders to a new folder,

# copy_source_images.py
import shutil
import sys
import os
import re

def copy_source_images(path, path_copied):
    Copy all images in folders/subfolders whose name not end with "???x???" to a new folder
    for root, _, files in os.walk(path):
        for name in files:
            if not re.match('.*-[0-9]{1,4}x[0-9]{1,4}.*', name):
                file_full_path = os.path.abspath(os.path.join(root, name))
                rst = shutil.copy(file_full_path, path_copied)
                if (rst):
                    print(f'✅ Copied "{name}" to {path_copied}')

if __name__ == "__main__":
    copy_source_images(sys.argv[1], sys.argv[2])

How to use it?

python copy_source_images.py /home/thi/Downloads/

Auto upload & attach & set featured images to posts

Require: posts are already attached with an featured image name.

This is useful when doing the previous step (moving all featured images from subfolders to a new folder). Each post has the featured image's information attached (the name and the path of the image). If you change the path of this image (on disk), you must also change the path in the post's data. We can do this by the name of the image and the title of the post.

Uncheck "Origanize my uploads in month- and year-based folders" in WP Admin > Settings > Media.

Get the list of posts with their data: WP Admin > GraphiQL IDE,