symdesign
11/14/2015 - 5:49 PM

Set a maximum space for media storage directory

//functions.php

$max_space = 1024*1024*600; // 600 MB

function get_dir_size($directory) {
    $size = 0;
    foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) {
        $size += $file->getSize();
    }
    return $size;
}
function human_filesize($size,$unit="") {
  if( (!$unit && $size >= 1<<30) || $unit == "GB") return number_format($size/(1<<30),2)." GB";
  if( (!$unit && $size >= 1<<20) || $unit == "MB") return number_format($size/(1<<20),2)." MB";
  if( (!$unit && $size >= 1<<10) || $unit == "KB") return number_format($size/(1<<10),2)." KB";
  return number_format($size)." bytes";
}
add_filter( 'wp_handle_upload_prefilter', 'before_uploading' );
function before_uploading( $file ) {
	global $max_space;

	$filesize = $file['size'];

	$upload_dir = wp_upload_dir();
	$used_space = get_dir_size($upload_dir['basedir']);

	if ( ($filesize + $used_space) > $max_space ) {
		$used_space_limit_reached = true;
	}

	if ( $used_space_limit_reached )
		$file['error'] = __('You reached the limit of', 'upload-quota-per-user').' '.human_filesize($max_space);

	return $file;
}