Use WP_Filesystem to list files in directory

Unfortunately the documentation about the Filesystem API is very basic. What you are looking for is the dirlist method/function of the WP_Filesystem_$method class(es). The only documentation about it is the docblock out of the WP_Filesystem_Base class:

/**
 * Get details for files in a directory or a specific file.
 *
 * @since 2.5.0
 *
 * @param string $path Path to directory or file.
 * @param bool $include_hidden Optional. Whether to include details of hidden ("." prefixed) files.
 *                             Default true.
 * @param bool $recursive Optional. Whether to recursively include file details in nested directories.
 *                        Default false.
 * @return array|bool {
 *     Array of files. False if unable to list directory contents.
 *
 *     @type string 'name' Name of the file/directory.
 *     @type string 'perms' *nix representation of permissions.
 *     @type int 'permsn' Octal representation of permissions.
 *     @type string 'owner' Owner name or ID.
 *     @type int 'size' Size of file in bytes.
 *     @type int 'lastmodunix' Last modified unix timestamp.
 *     @type mixed 'lastmod' Last modified month (3 letter) and day (without leading 0).
 *     @type int 'time' Last modified time.
 *     @type string 'type' Type of resource. 'f' for file, 'd' for directory.
 *     @type mixed 'files' If a directory and $recursive is true, contains another array of files.
 * }
 */
 public function dirlist( $path, $include_hidden = true, $recursive = false ) {
     return false;
 }

In the base class the method doesn’t actually have the functionality, for that take a look – for example – into the method declaration of dirlist inside the WP_Filesystem_Direct class.

Now lets get to how to use it, a basic example would look like this:

global $wp_filesystem;
$filelist = $wp_filesystem->dirlist( '/the/path/to/the/files/' );

Leave a Comment