Scan server directory

Hi,

Is there a possibility to scan a server directory content with L&L, in order to output a list a files name?

Apparently what the PHP scandir() functions does: How to list files in a directory in PHP

[EDIT] I can make a PHP shortcode and parse it in the L&L template as well.

L&L is currently just designed to loop through CPTs in specific WP tables and there isn’t a built-in mechanism to loop through custom tables, so I imagine navigating server files isn’t something L&L will be able to do for a while, if ever.

If you do use PHP to create a shortcode for that, I’d love to see it!

Hi @benjamin,

Sure, i understand.

Here’s my PHP shortcode to list files from a server directory:

<?php 
add_shortcode( 'list_directory_files', 'list_directory_files_fct' );
function list_directory_files_fct() {
	ob_start();

	$dirPath = 'wp-content/uploads/my-directory';

	// Check if directory exists
	if ( is_dir($dirPath) ) { ?>
		 <ul> 
			<?php
			// Get all PDF files in the directory
			$files = glob($dirPath . "/*.pdf");
			// Sort by natural order (e.g. digit 5 before 10…)
			natsort($files);

			foreach ($files as $file) {
				// Check if this is a file
				if ( is_file($file) ) {
					// Get file name
					$fileName = basename($file); ?>
					<li><a href="<?php echo site_url() . '/' . $file ?>"><?php echo $fileName ?></a></li>
				<?php }
			} ?>
		</ul> 
	<?php }

	return ob_get_clean();
}

Based on this tuto:

I used the PHP glob() function because it easily allows to filter files by type.

1 Like

If the files happen to be WP attachments, you could potentially access the data that way in L&L, but the PHP shortcode approach is probably the best outside of that.