Last active
June 14, 2017 20:40
-
-
Save agarzon/6938681 to your computer and use it in GitHub Desktop.
Explore Upload folder to remove unused files and save disk space. Wordpress shell script
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
<?php | |
/** | |
* Wordpress shell script | |
* Explore Upload folder to remove unused files and save disk space | |
* | |
* @category Wordpress | |
* @package Wordpress.shell | |
* | |
* @author Alexander Garzon <agarzon@php.net> | |
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License | |
* @link http://www.venehosting.com | |
*/ | |
if (!defined('ABSPATH')) { | |
/** Set up WordPress environment */ | |
require_once dirname(__FILE__) . '/wp-load.php'; | |
} | |
global $wpdb; | |
$uploadDir = wp_upload_dir(); | |
$toDelete = $toKeep = $errorDeleting = 0; | |
$start = new DateTime("now"); | |
//$path = $uploadDir["path"]; // for current month folder only | |
$path = $uploadDir["basedir"]; // for ALL folders in wp-content/uploads | |
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)); | |
foreach ($iterator as $file) { | |
if (!$file->isDir()) { | |
$subFolder = explode($uploadDir["basedir"], $file->getPath()); | |
$media = $subFolder[1] . '/' . $file->getFilename(); | |
$sqlPosts = "SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%{$media}%' LIMIT 1;"; | |
$mediaIsUsed = (boolean) $wpdb->get_var($sqlPosts); | |
if ($mediaIsUsed) { | |
++$toKeep; | |
} else { | |
++$toDelete; | |
if (@unlink($file->getRealPath())) { | |
++$toDelete; | |
} else { | |
++$errorDeleting; | |
} | |
} | |
} | |
} | |
echo "Time required: " . $start->diff(new DateTime("now"))->format('%H:%I:%S') . PHP_EOL; | |
echo "Kept files: $toKeep" . PHP_EOL; | |
echo "Deleted files: $toDelete" . PHP_EOL; | |
echo "Errors deleting: $errorDeleting" . PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment