Simple WP filter to modify media upload directory

Benefits of this: 

  • Faster Identification of Assets: By default, WordPress creates folders based on the id of the site. Changing this so folders are created based on the domain of the site makes asset folders easier to organize and identify.
  • Security: Altering WordPress defaults can thwart attacks from automated hacking scripts that just target certain default directories.

Multisite Example Code: 

function custom_upload_dir($upload) {

$defaultfolder = $_SERVER['SERVER_NAME'];
$blog_id = get_current_blog_id();
if ($blog_id == 15) { $folder = 'clientname'; }
else { $folder = $defaultfolder; }

  $path = array(
    'path' => WP_CONTENT_DIR . '/uploads/sites/',
    'url' => WP_CONTENT_URL . '/uploads/sites/',
    'subdir' => '',
    'basedir' => WP_CONTENT_DIR . '/uploads/sites/'.$folder,
    'baseurl' => WP_CONTENT_URL . '/uploads/sites/'.$folder,
    'error' => false,
  );
 
  return $path;

}
add_filter('upload_dir', 'custom_upload_dir');

If you’re changing some existing sites to a new structure you may have to do two things:

SQL Find and Replace Code:

update TABLE_NAME set FIELD_NAME =
replace(FIELD_NAME, 'Text to find', 'text to replace with');

Example on WP Posts:

update wp_posts set post_content =
replace(post_content,'Text to find','text to replace with');

GETTING OUTSIDE THE WP “WP-CONTENT” DIRECTORY:

function custom_upload_dir($upload) {

$siteurl = get_site_url();
$root = $_SERVER["DOCUMENT_ROOT"];

$defaultfolder = $_SERVER['SERVER_NAME'];
$blog_id = get_current_blog_id();

if ($blog_id == 15) { $folder = 'clientname'; }
else { $folder = $defaultfolder; }

  $path = array(
    'path' => $root . '/media/',
    'url' => $siteurl . '/media/',
    'subdir' => '',
    'basedir' => $root . '/media/'.$folder,
    'baseurl' => $siteurl . '/media/'.$folder,
    'error' => false,
  );
 
  return $path;

}
add_filter('upload_dir', 'custom_upload_dir');

If you’re on certain shared hosting environments you may run into trouble getting directories that aren’t subs of the “/sites/” folder to work properly because of permissions imposed and enforced by your host but it is possible and it’s nice if all your files are store more at yourdomain.com/media/ instead of the longer default directory from WordPress.