Using WordPress ‘list_files()’ PHP function

The list_files() WordPress PHP function returns a listing of all files in the specified folder and all subdirectories up to 100 levels deep.

Usage

list_files($folder = '', $levels = 100, $exclusions = array())

Parameters

  • $folder (string): Optional. Full path to the folder. Default: ”.
  • $levels (int): Optional. Levels of folders to follow. Default: 100 (PHP loop limit).
  • $exclusions (array): Optional. List of folders and files to skip. Default: array().

More information

See WordPress Developer Resources: list_files()

Examples

Listing all files in the uploads directory

In this example, we list all files in the WordPress uploads directory and display the file name and file size.

$upload_dir = wp_upload_dir();
$folder = $upload_dir['basedir'];
$files = list_files($folder, 2);

foreach ($files as $file) {
    if (is_file($file)) {
        $filesize = size_format(filesize($file));
        $filename = basename($file);
    }
    echo esc_html($filename . '-' . $filesize);
}

Listing all files in the current directory

This example lists all files in the current directory and prints their absolute paths.

$files = list_files(__DIR__);
print_r($files);

Listing files with limited folder depth

In this example, we limit the folder depth to 1 level when listing files.

$folder = '/path/to/your/folder';
$files = list_files($folder, 1);
print_r($files);

Excluding specific files and folders

This example demonstrates how to exclude specific files and folders from the listing.

$folder = '/path/to/your/folder';
$exclusions = array('exclude_folder', 'exclude_file.txt');
$files = list_files($folder, 100, $exclusions);
print_r($files);

Listing files in a custom theme folder

In this example, we list all files in a custom theme folder called “mytheme”.

$theme_folder = get_template_directory() . '/mytheme';
$files = list_files($theme_folder);
print_r($files);