Creating a hashed upload directory structure in wordpress for sites with large amounts of files

Posted on July 10th, 2019

The problem:

A site has 2.4+ million uploads in wordpress for one month. The site was extremely slow because of so many files in a single directory. 2 million files with in wp-content/uploads/2019/07

Looking around there was surprisingly no plugin I found that handled this in any way. So I went to writing something for this user. So I found https://codex.wordpress.org/Plugin_API/Filter_Reference/upload_dir which showed ways to change the upload folder. I used this to create a set up where two random letters are made – keeping the standard upload folder set up in tact. In this case

wp-content/uploads/2019/07

becomes

wp-content/uploads/2019/07/a/b

A letter bettwen a to z is selected at random twice to generate the new upload folder.

To activate this plugin on the user site I created a file called upload_file_hash.php under wp-content/mu-plugins with the below code

<?php
/*
Plugin Name: upload folder hash
Description: hash upload folder for large amount of files https://codex.wordpress.org/Plugin_API/Filter_Reference/upload_dir
Author: John Quaglieri
Version: 1.0.0
Author URI: http://interserver.net
*/

function upload_folder_hash( $param ){
$letter = chr(rand(97,122));
$letter2 = chr(rand(97,122));
$folder = ‘/’ . $letter . ‘/’ . $letter2;
$mydir = $folder;
$param[‘path’] = $param[‘path’] . $mydir;
$param[‘url’] = $param[‘url’] . $mydir;
return $param;
}

add_filter(‘upload_dir’, ‘upload_folder_hash’);

Once done all new uploads in media used the new folder structure. Problem solved.

One Response to “Creating a hashed upload directory structure in wordpress for sites with large amounts of files”

  1. salem says:

    thanks for making this for us appreciate it. best experience with a hosting service

Leave a Reply