Add media storage amount to wpms sites view

For one of our multisites, I wanted an easy way to see show people the media storage usage per site.

I did a bit of Googling and got a couple functions to get the size of a directory using PHP.1

Then I just appended it to the column I’d already customized to show the posts and page count.

Seems to work pretty well but it hasn’t been tested on a big multisite. It’d be easy enough to tie it to individual sites and run it on media library change, then store the data rather than call it live for the network sites view.

Here are the WP functions.

// Hook to manage column data on network sites listing
add_action( 'manage_sites_custom_column', 'rampages_sites_custom_column', 10, 2 );

/**
* Show page post/page count and file storage
*
* @param string
* @param integer
*
* @return void
*/
function rampages_sites_custom_column($column_name, $blog_id)
{
    if ( $column_name == 'content' ) {
           switch_to_blog($blog_id);
           $full_media_path = wp_upload_dir()['path'];//get upload directory path
           if($blog_id === 1){
             $media_folder_top = $full_media_path;
           } else {
             $media_folder_top = substr($full_media_path,0,strlen($full_media_path)-7);
           }
     
           $file_size = human_filesize(GetDirectorySize($media_folder_top),0);
            $pages = wp_count_posts('page','publish')->publish;
            $posts = wp_count_posts('post', 'publish')->publish;
    restore_current_blog();
   
    if ($posts < 1){
        $posts = 0;
    }
if ($pages < 1){
        $pages = 0;
    }
        echo  $posts . '/' . $pages . '/' . $file_size;
    }
}

//make size human
//https://stackoverflow.com/questions/15188033/human-readable-file-size
function human_filesize($bytes, $decimals = 2) {
    $factor = floor((strlen($bytes) - 1) / 3);
    if ($factor > 0) $sz = 'KMGT';
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor - 1] . 'B';
}

//get size
//https://stackoverflow.com/a/21409562/3390935
function GetDirectorySize($path){
    $bytestotal = 0;
    $path = realpath($path);
    if($path!==false && $path!='' && file_exists($path)){
        foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object){
            $bytestotal += $object->getSize();
        }
    }
    return $bytestotal;
}

1 Thinking about it now, there has to be some WP function that does something like this in order to restrict total storage in multisite.

Leave a Reply