Skip to content

Instantly share code, notes, and snippets.

@torrottum
Created July 7, 2016 13:28
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 torrottum/b4ba24cf6084c53e6f4e2fd621b790b1 to your computer and use it in GitHub Desktop.
Save torrottum/b4ba24cf6084c53e6f4e2fd621b790b1 to your computer and use it in GitHub Desktop.
Remove uploads from WordPress that doesn't exist in the database
#!/usr/bin/env python3
from subprocess import Popen,PIPE,STDOUT
import sys
import os
"""
Removes all WordPress attachments that doesn't exist in the database
You need to be inside your uploads folder
RUN AT YOUR OWN RISK! (You should probably take a backup of the uploads dir)
"""
if os.path.basename(os.getcwd()) != 'uploads':
print('Not in uploads folder!')
sys.exit(1)
username=input("MySQL username: ")
database=input("MySQL database: ")
mysql = Popen( ['mysql', '-u', username, '-p', '-s', '-N', '-e', "SELECT meta_value from wp_postmeta WHERE meta_key = '_wp_attached_file' and post_id IN (SELECT id from wp_posts WHERE post_type='attachment')", database], stderr=STDOUT, stdout=PIPE)
output = mysql.communicate()[0].decode('UTF-8')
if mysql.returncode != 0:
print(output)
sys.exit(1)
keep = output.split('\n')
del keep[-1:]
keep = list(map(lambda f: './' + f, keep))
for root, dirs, files in os.walk('.'):
for file in files:
file = os.path.join(root, file)
if file not in keep:
print('Deleting %s' % file)
os.remove(file)
else:
print('Keeping %s' % file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment