Function and usage of recurse_dirsize() in wordpress


Answers ( 1 )


    The recurse_dirsize() function in WordPress is a utility function used to calculate the total size of a directory, including all its subdirectories. Here's a detailed explanation of its usage and parameters:


    • Name: recurse_dirsize
    • Purpose: To get the size of a directory recursively, including the sizes of all its subdirectories.


    • The function is primarily used by get_dirsize() to calculate the size of a directory when that directory contains other directories.
    • It's a part of WordPress's file management utilities, helping in assessing disk space usage.


    1. $directory (string, required):

      • Description: Full path of the directory whose size you want to calculate.
      • Example: '/path/to/wordpress/uploads'
    2. $exclude (string|string[], optional):

      • Description: Path or an array of paths of subdirectories to exclude from the total size calculation. Paths should be specified without trailing slashes.
      • Default: null
      • Example: '/path/to/wordpress/uploads/exclude' or ['/exclude1', '/exclude2']
    3. $max_execution_time (int, optional):

      • Description: Maximum time allowed for the function to run before it gives up. The time is measured in seconds from when WordPress started loading.
      • Default: Value of the max_execution_time PHP setting.
      • Example: 30 (for 30 seconds)
    4. $directory_cache (array, optional):

      • Description: An array of cached directory paths. This can be used to optimize performance by reusing previously computed sizes.
      • Default: Value of the dirsize_cache transient.
      • Example: ['/path1' => 12345, '/path2' => 67890]

    Return Values:

    • Type: int|false|null
    • Description:
      • Returns the size in bytes if a valid directory is provided and processed successfully.
      • Returns false if the provided path is not a valid directory.
      • Returns null if a timeout occurs (as determined by $max_execution_time).

    Sample Usage:

    $directory = '/path/to/wordpress/uploads';
    $exclude = ['/path/to/wordpress/uploads/cache'];
    $max_execution_time = 30; // 30 seconds
    $directory_cache = ['cached_dir_path' => 1024]; // Example cache
    $size = recurse_dirsize($directory, $exclude, $max_execution_time, $directory_cache);
    if ($size !== false && $size !== null) {
        echo "Directory size: " . $size . " bytes";
    } else {
        echo "Could not calculate directory size.";

    In this example, recurse_dirsize() is used to calculate the size of a WordPress uploads directory, excluding a specific cache directory, with a maximum execution time of 30 seconds and utilizing a simple directory size cache.

Leave an answer