public
Last active

Check WordPress core for unused images.

  • Download Gist
wp-search-images.sh
Shell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#!/bin/bash
# Checks WordPress core for unused images.
# Requires ack2: http://beyondgrep.com/
#
# The script needs to be placed inside the WordPress root
# directory or add the path to the WordPress directory via a
# parameter. Example: $ ./wp-search-images ~/Sites/WordPress/
#
# Define the image paths in img_paths[]
#
# Author: Dominik Schilling, 2012-2013
# https://core.trac.wordpress.org/ticket/20980
# https://core.trac.wordpress.org/ticket/26036
 
# Image paths
img_paths[0]='wp-admin/images';
img_paths[1]='wp-includes/images';
 
# Get the WordPress root
wp_root='./'
if [ $1 ] && [ ! -d ${1} ]
then
echo "Wrong path!"
exit;
else
if [ $1 ]
then
wp_root=$1
fi
fi
 
# Check if it's WordPress
if [ ! -f $wp_root/wp-settings.php ]
then
echo "No WordPress directory detected!"
exit
fi
 
# Get the images and search through WordPress if the image is used. Magic.
for path in "${img_paths[@]}"
do
for image in `find $wp_root$path -name "*.gif" -o -name "*.jpg" -o -name "*.png" -o -name "*.jpeg" | grep -v 'crystal'`
do
image_name=`basename $image`
image_file=`echo $image | sed 's|'$wp_root'||'`
 
printf "\nSearching for $image_file\n"
 
res=`ack "$image_name" $wp_root -l --ignore-dir=wp-content --ignore-file=match:update-core.php`
if [ $1 ] && [ $1 == -s ] || [ $2 ] && [ $2 == -s ]
then
printf "\t%s\n" $res
fi
if [ -z "$res" ]
then
printf "No match!\n"
unused_images=("${unused_images[@]}" "$image_file")
else
printf "%d matches!\n" `echo "$res" | wc -l`
 
fi
done
done
 
 
# Print the results
printf "\n=================================================="
printf "\n%d images with 0 matches:\n\n" ${#unused_images[@]}
for unused_image in "${unused_images[@]}"
do
printf "%s\n" "$unused_image"
done

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.