Created
July 7, 2016 13:28
-
-
Save torrottum/b4ba24cf6084c53e6f4e2fd621b790b1 to your computer and use it in GitHub Desktop.
Remove uploads from WordPress that doesn't exist in the database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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