Skip to content

Instantly share code, notes, and snippets.

@agarzon
Last active June 14, 2017 20:40
Show Gist options
  • Save agarzon/6938681 to your computer and use it in GitHub Desktop.
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
<?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