The recurse_dirsize() WordPress PHP function is used to calculate the size of a directory, including all its subdirectories and files.
Usage
$directory_size = recurse_dirsize($directory, $exclude, $max_execution_time, $directory_cache);
Parameters
$directory
(string) (Required): Full path of the directory.$exclude
(string|string[]) (Optional): Full path of a subdirectory or an array of paths to exclude from the total. Expected without trailing slash(es). Default: null$max_execution_time
(int) (Optional): Maximum time to run before giving up, in seconds. The timeout is global and is measured from the moment WordPress started to load. Defaults to the value ofmax_execution_time
PHP setting. Default: null$directory_cache
(array) (Optional): Array of cached directory paths. Defaults to the value ofdirsize_cache
transient. Default: null
More information
See WordPress Developer Resources: recurse_dirsize
Examples
Calculate the size of a directory
This code calculates the size of the “uploads” directory located in the WordPress “wp-content” folder.
$uploads_dir = wp_upload_dir()['basedir']; $directory_size = recurse_dirsize($uploads_dir); echo 'The size of the uploads directory is: ' . $directory_size . ' bytes.';
Calculate the size of a directory, excluding a subdirectory
This code calculates the size of the “wp-content” directory, excluding the “plugins” subdirectory.
$wp_content_dir = WP_CONTENT_DIR; $exclude = $wp_content_dir . '/plugins'; $directory_size = recurse_dirsize($wp_content_dir, $exclude); echo 'The size of the wp-content directory without plugins is: ' . $directory_size . ' bytes.';
Calculate the size of a directory, excluding multiple subdirectories
This code calculates the size of the “wp-content” directory, excluding the “plugins” and “themes” subdirectories.
$wp_content_dir = WP_CONTENT_DIR; $exclude = array($wp_content_dir . '/plugins', $wp_content_dir . '/themes'); $directory_size = recurse_dirsize($wp_content_dir, $exclude); echo 'The size of the wp-content directory without plugins and themes is: ' . $directory_size . ' bytes.';
Calculate the size of a directory with a custom timeout
This code calculates the size of the “uploads” directory with a custom timeout of 10 seconds.
$uploads_dir = wp_upload_dir()['basedir']; $max_execution_time = 10; $directory_size = recurse_dirsize($uploads_dir, null, $max_execution_time); echo 'The size of the uploads directory is: ' . $directory_size . ' bytes.';
Calculate the size of a directory using a directory cache
This code calculates the size of the “uploads” directory using a custom directory cache.
$uploads_dir = wp_upload_dir()['basedir']; $directory_cache = get_transient('dirsize_cache'); $directory_size = recurse_dirsize($uploads_dir, null, null, $directory_cache); echo 'The size of the uploads directory is: ' . $directory_size . ' bytes.';