Skip to content

Instantly share code, notes, and snippets.

@stephenfeather
Created February 27, 2023 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephenfeather/3c5a74dcf3aa9600806c0f42fbb02d93 to your computer and use it in GitHub Desktop.
Save stephenfeather/3c5a74dcf3aa9600806c0f42fbb02d93 to your computer and use it in GitHub Desktop.
Bash script to deleted wordpress attachments that have a bad URL (WIP)
#!/usr/bin/bash
BASE_URL="https://myourdomain.com/files/"
# We need to be able to trap breakouts
trap exit_script INT
function exit_script() {
end=`date +%s.%N`
runtime=$( echo "$end - $start" | bc -l )
echo " "
echo $MESSAGE
echo "Last Record Processed: "$LAST_PROCESSED
echo "Elapsed Time: "$runtime
echo "Processed: "$PROCESSED
echo "Deleted: "$DELETED
exit 1
}
start=`date +%s.%N`
LOW=$1
HIGH=$2
PROCESSED=0
DELETED=0
LAST_PROCESSED=0
MESSAGE=""
if [ $LOW -gt $HIGH ]; then
MESSAGE="Inverted range: $LOW > $HIGH"
exit_script
fi
for ID in $(wp post list --order=ASC --post_type='attachment' --format=ids);
do
#echo $ID
# Exit script if $ID is 0, meaning no return values
if (( $ID == 0 )); then
MESSAGE="No records found."
exit_script
fi
# We only want to process $IDs within a range if range given
# We must be greater or equal to $LOW
if [ ! -z $LOW ]; then
#echo "Low has value"
if [ $ID -lt $LOW ]; then
#echo "$ID LESS THAN $LOW"
continue
fi
fi
# We must be lower or equal to $HIGH
if [ ! -z $HIGH ]; then
#echo "High has value"
if [ $ID -gt $HIGH ]; then
#echo "$ID GREATER THAN $HIGH"
MESSAGE="Upper limit of range reached"
exit_script
fi
fi
# Get the url for the attachments file
LAST_PROCESSED=$ID
PROCESSED=$((PROCESSED+1))
IMAGE_URL=$(wp post meta get $ID _wp_attached_file)
# We want to check remote access through the CND
# so prepend the cdn
IMAGE_URL=$BASE_URL$IMAGE_URL
# run the url through curl and return the http code
CODE=$(curl -s -o /dev/null -I -w "%{http_code}" $IMAGE_URL)
# if the http code is a 404
if [ $CODE == "404" ]; then
# Delete the attachment
DELETED_RESPONSE=$(wp post delete $ID --force --defer-term-counting)
echo $DELETED_RESPONSE
DELETED=$((DELETED+1))
fi
done
wait
exit_script
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment