Regenerate image sizes for specific posts
I have a custom post type called lfh_home
, which uses an image size called card-header
on post listing pages.
When I make changes to that image size for testing, I want to regenerate the thumbnails/generated media, but don't want to do it to all 3000+ images on the site.
The goal here is to get the posts of the lfh_home
post type, get the ID of the featured image (stored in the _thumbnail_id
post meta field), and regenerate just the card-header
image.
A regular wp media regenerate --image_size=card-header
task takes approximately 12m24s to process 2971 images in local testing. This script takes 44s to process 10 images on the same machine.
chmod +x regenerate-images-for-post-type.sh
./regenerate-images-for-post-type.sh <post_type> <image_size>
, where post_type
is your post type (default 'post') and image_size
is an image size registered with WordPress (default 'thumbnail').#!/usr/bin/env bash
wproot() {
wp --allow-root "$@"
}
wp_regenerate_thumbnails() {
declare -a thumbnail_ids
local post_type=${1:-post}
local image_size=${2:-thumbnail}
local thumbnail_id
printf "Getting images to regenerate...\\n\\n"
for post_id in $(wproot post list --post_type="${post_type}" --field=ID); do
thumbnail_id="$(wproot post meta get "${post_id}" _thumbnail_id)"
if [[ -n "${thumbnail_id}" ]]; then
thumbnail_ids+=("${thumbnail_id}")
fi
done
printf "Regenerating %d \"%s\" images for \"%s\" posts...\\n\\n" ${#thumbnail_ids[@]} "${image_size}" "${post_type}"
for image_id in "${thumbnail_ids[@]}"; do
wproot media regenerate "${image_id}" --image_size="${image_size}"
done
printf "Done regenerating images for \"%s\".\\n\\n" "${post_type}"
}
wp_regenerate_thumbnails "$1" "$2"