Skip to content

Instantly share code, notes, and snippets.

@mfyz
Created February 14, 2021 22:16
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 mfyz/d0f9deabe98a01ef322bc6244b8eed4a to your computer and use it in GitHub Desktop.
Save mfyz/d0f9deabe98a01ef322bc6244b8eed4a to your computer and use it in GitHub Desktop.
wordpress clean up uploads folder (scan files and check in the DB/media-library then delete unmapped ones)
<?php
require(__DIR__ . '/../wp-load.php');
if (!function_exists('wp')) die('Sorry, looks like WordPress isn\'t loaded.');
$dry_run = true;
$move_files_to_trash_folder = true;
$trash_folder_path = realpath(__DIR__ . '/..') . '/unmapped-uploads-to-delete';
if ($move_files_to_trash_folder && !file_exists($trash_folder_path)) mkdir($trash_folder_path);
$query_images_args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_status' => 'inherit',
'posts_per_page' => -1,
);
$query_images = new WP_Query( $query_images_args );
$media_library = array();
foreach ($query_images->posts as $image) {
$file = strstr(wp_get_attachment_url( $image->ID ), 'wp-content');
$file = trim(strrev(strstr(strrev($file), '.')), '.');
if ($file) $media_library[] = $file;
}
// var_dump($media_library); exit;
function getFilesArray($path) {
return array_diff(scandir($path), array('.', '..'));
}
function checkFileExistsInMediaLibrary($path) {
$files = getFilesArray($path);
foreach ($files as $filename) {
$filepath = realpath($path . '/' . $filename);
if (substr(strstr($filepath, 'wp-content'), 0, 21) !== 'wp-content/uploads/20') continue;
if (is_dir($filepath)) {
checkFileExistsInMediaLibrary($filepath);
}
else {
$filesearch = strstr($filepath, 'wp-content'); // just the relative path
$filesearch = trim(strrev(strstr(strrev($filesearch), '.')), '.'); // lose extension
$filesearch = preg_replace('/-[0-9]{2,4}x[0-9]{2,4}$/', '', $filesearch);
if (!in_array($filesearch, $GLOBALS['media_library'])) {
if ($GLOBALS['dry_run']) {
print $filepath . " not found! (dry run)\n";
}
else if ($GLOBALS['move_files_to_trash_folder']) {
$target_path = $GLOBALS['trash_folder_path'] . '/' . basename($filepath);
if (rename($filepath, $target_path)) {
print $filepath . " not found and moved to trash folder!\n";
}
else {
print $filepath . " COULD NOT BE MOVED TO TRASH!\n";
}
}
else {
if (unlink($filepath)) {
print $filepath . " not found and deleted!\n";
}
else {
print $filepath . " COULD NOT BE DELETED!\n";
}
}
}
}
}
}
checkFileExistsInMediaLibrary(__DIR__ . '/../wp-content/uploads/');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment