+91 88 00 56 3434 

sales@webhostingpeople.net 

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

You are here:

The problem:

A website has over 2.4 million uploads in WordPress within one month. The location was exceptionally sluggish due to the overwhelming number of files in a single directory. There are 2 million files within wp-content/uploads/2019/07.

After searching around, I surprisingly found no plugin that addressed this issue. So, I decided to write something for this client. I came across https://codex.wordpress.org/Plugin_API/Filter_Reference/upload_dir which demonstrated how to change the upload folder. I used this to create a setup where two random letters are generated while keeping the standard upload folder structure intact. In this case, wp-content/uploads/2019/07 becomes wp-content/uploads/2019/ 07/a/b.

A random pair of letters, chosen from a to z, is generated twice to form the new upload folder.

To activate this plugin on the client website, I created a file called upload_file_hash.php under wp-content/mu-plugins with the following code:

<?php
/*
Plugin Title: upload folder hash
Description: Hash the upload folder for a large amount of files using https://codex.wordpress.org/Plugin_API/Filter_Reference/upload_dir
Creator: John Quaglieri
Version: 1.0.0
Creator URI: http://webhostingpeople.internet
*/

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 completed, all new uploads in the media will use the new folder structure. Problem solved.

Leave a Comment

Table of Contents
WebHostingPeople
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.