Skip to content

Instantly share code, notes, and snippets.

@kshojib
Last active November 5, 2024 11:52
Show Gist options
  • Save kshojib/cc1494a2fcdddc64cf2d759b784552c4 to your computer and use it in GitHub Desktop.
Save kshojib/cc1494a2fcdddc64cf2d759b784552c4 to your computer and use it in GitHub Desktop.
Add this file to root directory. Make the script executable: chmod +x regenerate-images.sh Then run this command ./regenerate-images.sh
#!/bin/bash
# Set the admin user with the right permissions (replace with the actual username or user ID)
ADMIN_USER="shojib"
CATEGORY_ID=2721
PAGE=1
PER_PAGE=90
PRODUCT_IDS=""
# Loop to fetch all product IDs page by page
while true; do
# Fetch a page of products in the specified category
PAGE_PRODUCT_IDS=$(wp wc product list --category=$CATEGORY_ID --format=ids --user=$ADMIN_USER --page=$PAGE --per_page=$PER_PAGE)
# Break the loop if no more products are found
if [ -z "$PAGE_PRODUCT_IDS" ]; then
break
fi
# Append the IDs from the current page to the list of all product IDs
PRODUCT_IDS="$PRODUCT_IDS $PAGE_PRODUCT_IDS"
# Move to the next page
PAGE=$((PAGE + 1))
done
# Check if any products are found
if [ -z "$PRODUCT_IDS" ]; then
echo "No products found in the '2743' category."
exit 1
fi
echo "Products found in the '2743' category: $PRODUCT_IDS"
# Loop through each product ID
for PRODUCT_ID in $PRODUCT_IDS
do
# Get the featured image ID for each product
FEATURED_IMAGE_ID=$(wp post meta get $PRODUCT_ID _thumbnail_id)
# Get the gallery image IDs (stored as a comma-separated list in '_product_image_gallery')
GALLERY_IMAGE_IDS=$(wp post meta get $PRODUCT_ID _product_image_gallery)
# Combine featured image and gallery images into one list of IDs
if [ -n "$FEATURED_IMAGE_ID" ] || [ -n "$GALLERY_IMAGE_IDS" ]; then
ALL_IMAGE_IDS="$FEATURED_IMAGE_ID $GALLERY_IMAGE_IDS"
echo "Regenerating images for product ID $PRODUCT_ID..."
echo "Images: $ALL_IMAGE_IDS"
echo "$ALL_IMAGE_IDS" | tr ',' '\n' | xargs wp media regenerate --yes --user=$ADMIN_USER
else
echo "No images found for product ID $PRODUCT_ID, skipping..."
fi
done
echo "Regeneration of featured and gallery images complete!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment