Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Steingrímur F. Stefánsson
seal-mask
PLUS
.a{fill-rule:evenodd;}techdegree seal-36
Steingrímur F. Stefánsson
Front End Web Development Techdegree Graduate 33,699 Points

Add directory content, filename, to array is not working in WP [SOLVED]

Hi all.

I'm working on custom WP template and I'd like to add a variable that include a random image file name that comes from an array. I will then use this variable in <img> tag.

I have tried this php script outside WP website and it's working there.

The problem seems to be in the array part and what I think is that the scandir is not able to read or retrieve filelist from given path from $directory variable.

I'm starting to think that WP does not allow directory scan. What do you think?

Here is the code:

<?php
$directory = get_bloginfo('template_directory') . '/images/banners/header-images/';

$scanned_directory = array_diff(scandir($directory), array('..', '.'));

$rand_images = array_rand($scanned_directory, 1);

echo '<br><br>';
print_r($scanned_directory); //This command does not print the array to screen
?>
Steingrímur F. Stefánsson
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Steingrímur F. Stefánsson
Front End Web Development Techdegree Graduate 33,699 Points

I had to use wp_upload_dir() instead of bloginfo() to be able to get the filelist.

<?php
$directory = wp_upload_dir();       

$scanned_directory = array_diff(scandir($directory['basedir'] . '/banners/header-images'), array('..', '.'));
$rand_images = array_rand($scanned_directory);
?>