Skip to content

Instantly share code, notes, and snippets.

@torrottum torrottum/remove.py
Created Jul 7, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.