Using WordPress ‘recurse_dirsize’ PHP function

recurse_dirsize() is a WordPress PHP function that calculates the size of a directory, including all its subdirectories and files.

It’s particularly useful when you need to determine the total size of a directory with multiple nested subdirectories.

Usage

To use recurse_dirsize(), provide the required $directory parameter, along with any optional parameters as needed.

$size = recurse_dirsize($directory, $exclude, $max_execution_time, $directory_cache);

Parameters

  • $directory (string) – Required. The full path of the directory.
  • $exclude (string|string[]) – Optional. The full path of a subdirectory to exclude from the total size calculation, or an array of paths. Don’t include a trailing slash. Default: null.
  • $max_execution_time (int) – Optional. The maximum time (in seconds) the function should run before stopping. The timeout starts when WordPress begins loading. If not provided, it defaults to the max_execution_time PHP setting. Default: null.
  • $directory_cache (array) – Optional. An array of cached directory paths. If not provided, it defaults to the dirsize_cache transient. Default: null.

Examples

Basic directory size calculation

$directory = "/path/to/your/directory";
$size = recurse_dirsize($directory);

This code calculates the size of the specified directory, including all its subdirectories and files.

Excluding a specific subdirectory

$directory = "/path/to/your/directory";
$exclude = "/path/to/your/directory/subdir_to_exclude";
$size = recurse_dirsize($directory, $exclude);

This code calculates the size of the specified directory but excludes the size of the given subdirectory.

Excluding multiple subdirectories

$directory = "/path/to/your/directory";
$exclude = [
  "/path/to/your/directory/subdir1_to_exclude",
  "/path/to/your/directory/subdir2_to_exclude"
];
$size = recurse_dirsize($directory, $exclude);

This code calculates the size of the specified directory but excludes the sizes of multiple subdirectories.

Setting a custom maximum execution time

$directory = "/path/to/your/directory";
$max_execution_time = 10; // 10 seconds
$size = recurse_dirsize($directory, null, $max_execution_time);

This code calculates the size of the specified directory with a custom maximum execution time of 10 seconds.

Using a custom directory cache

$directory = "/path/to/your/directory";
$directory_cache = [
  "/path/to/your/directory/subdir1" => 1024,
  "/path/to/your/directory/subdir2" => 2048
];
$size = recurse_dirsize($directory, null, null, $directory_cache);

This code calculates the size of the specified directory using a custom directory cache for improved performance.