WordPress at a glance

get_dirsize() WP 3.0.0

Gets the size of a directory in bytes. The result is cached to temporary options: get_transient().

A helper function that is used primarily to check whether multisite blog has exceeded its allowed uploads space.

The function is defined only for Multisite WordPress installation. In order to make it available for the single website installation, you need to include this file:

require_once ABSPATH . WPINC .'/ms-functions.php';
Works based on: recurse_dirsize()

No Hooks.

Return

Int/false. Size of the directory in bytes. False if the directory doesn't exist.

Usage

get_dirsize( $directory, $max_execution_time );
$directory(string) (required)
Full path of a directory.
$max_execution_time(int)
Maximum time to run before giving up. In seconds. The timeout is global and is measured from the moment WordPress started to load.
Default: null

Examples

#1 Get the full size of uploads directory

$upload_dir = wp_upload_dir();

// include necessary functions
require_once ABSPATH . WPINC .'/ms-functions.php';

$mb = get_dirsize( $upload_dir['basedir'] );

echo number_format( $mb / (1024*1024), 1 ) .' MB'; // output: 93.2 MB

Code of get dirsize: wp-includes/functions.php WP 5.2.1

<?php
function get_dirsize( $directory, $max_execution_time = null ) {
	$dirsize = get_transient( 'dirsize_cache' );

	if ( is_array( $dirsize ) && isset( $dirsize[ $directory ]['size'] ) ) {
		return $dirsize[ $directory ]['size'];
	}

	if ( ! is_array( $dirsize ) ) {
		$dirsize = array();
	}

	// Exclude individual site directories from the total when checking the main site of a network
	// as they are subdirectories and should not be counted.
	if ( is_multisite() && is_main_site() ) {
		$dirsize[ $directory ]['size'] = recurse_dirsize( $directory, $directory . '/sites', $max_execution_time );
	} else {
		$dirsize[ $directory ]['size'] = recurse_dirsize( $directory, null, $max_execution_time );
	}

	set_transient( 'dirsize_cache', $dirsize, HOUR_IN_SECONDS );
	return $dirsize[ $directory ]['size'];
}

Related Functions

From tag: File system (create delete files folders)

More from category: Multisite

No comments
    Hello, !     Log In . Register