How to get all files from a folder in php, wordpress

To retrieve all files from a folder in PHP, including within WordPress, you can use the glob() or scandir() functions. Both methods are convenient and flexible for working with files.

1. Using glob()

The glob() function returns an array of filenames and directories that match a specified pattern. Here’s an example:

$directory = '/path/to/your/directory/*'; // Path to your directory
$files = glob($directory);

foreach ($files as $file) {
    if (is_file($file)) {
        echo basename($file) . "<br>";
    }
}

In this example:

  • * represents all files in the directory.
  • basename($file) is used to get the filename without the full path.

2. Using scandir()

The scandir() function returns an array of files and folders from the specified directory.

$directory = '/path/to/your/directory/';
$files = scandir($directory);

foreach ($files as $file) {
    if (is_file($directory . $file)) {
        echo $file . "<br>";
    }
}

How to Use This in WordPress

If you are working within a WordPress theme or plugin, you can use WordPress functions to get the correct paths. For example:

$directory = get_template_directory() . '/your-folder/';
$files = scandir($directory);

foreach ($files as $file) {
    if (is_file($directory . $file)) {
        echo $file . "<br>";
    }
}

In this example, the get_template_directory() function is used to return the path to the current WordPress theme.

Note

  • Make sure you have the correct permissions to access the folder. In WordPress, it’s often useful to use WP functions like wp_upload_dir() to securely access uploaded files.

How useful is the publication?

Click on a star to rate it!

Average score 5 / 5. Number of grades: 1

No ratings yet. Rate it first.

Similar posts

How to exclude posts with parent post in wp_query, WordPress

To exclude posts that have a parent (i.e., child posts) in a WP_Query request, you can use the post_parent argument. This argument controls whether the post has a parent or not. To exclude child posts, set the condition post_parent => 0, which means that only top-level posts (posts without a parent) will be included in…
Read more