Give WordPress Media Thumbnails Their Own Directory

If, like me, you find WordPress incredibly messy in the way it fills up your media folder with a noise of rebuilt thumbnails here is a little code for your functions.php

It will create future thumbnails in their own /thumbnails/ directory within your media folder.

function custom_thumbnail_save_directory($metadata, $attachment_id) {
$custom_subdir = '/thumbnails/';

$upload_dir = wp_upload_dir();
$custom_dir = $upload_dir['basedir'] . $custom_subdir;

if (!file_exists($custom_dir)) {
mkdir($custom_dir, 0755, true);
}

if (!empty($metadata['sizes'])) {
foreach ($metadata['sizes'] as $size => $size_info) {
$source_file = $upload_dir['path'] . '/' . $size_info['file'];
$destination_file = $custom_dir . '/' . $size_info['file'];

if (file_exists($source_file)) {
rename($source_file, $destination_file);
}

$metadata['sizes'][$size]['file'] = 'thumbnails/' . $size_info['file'];
}
}

return $metadata;
}
add_filter('wp_generate_attachment_metadata', 'custom_thumbnail_save_directory', 10, 2);

function custom_thumbnail_directory($uploads) {
$custom_subdir = '/thumbnails/';

if (!file_exists($uploads['basedir'] . $custom_subdir)) {
mkdir($uploads['basedir'] . $custom_subdir, 0755, true);
}

return $uploads;
}
add_filter('upload_dir', 'custom_thumbnail_directory');

Use a plugin to rebuild your thumbs after adding this code. Now, isn’t that tidy?

Leave a Reply