taming wp_upload_dir to create a directory with the name you want instead of a date

First I guess I need to answer “why” and there are probably two of them

  • Why do I care that it creates a date based directory even if not needed?
    Because I hate to waste CPU cycles if it can be avoided with almost no effort, and I hate to see empty directories when I need to traverse the uploads tree with an FTP software
  • Why not take the base directory from the value being returned and create the directory by myself?
    Because I prefer to trust the core APIs over my own code whenever possible. Core code is tested in real life by millions every day on different platforms and I will probably never test it on more then one. So while creating a directory seems like a very easy thing to do I sill prefer avoid thinking about the possible caveats that might be specific to a specific OS.

The code is actually easy, this is a snippet of something I work on right now


// returns the directory into which the files are stored
function mk_flf_dir() {
  add_filter('upload_dir','mk_flf_upload_dir',10,1);
  $dirinfo = wp_upload_dir();
  remove_filter('upload_dir','mk_flf_upload_dir',10,1);

  return $dirinfo['path'];
}

// override the default directory about to be created by wp_upload_dir
function mk_flf_upload_dir($info) {
  $info['path'] = $info['basedir'].'/fast_logins';
  return $info;
}

The fine point here is to remove the filter after it has done its thing, just because there is a slight chance some other code will want to call wp_upload-dir after your code had run.

 

Leave a Reply

Your email address will not be published. Required fields are marked *