Forums

[resolved] List files in directory. Works everywhere BUT wordpress. (5 posts)

  1. shovelshed
    Member
    Posted 7 months ago #

    Hi,

    I have the following code i'm using to display all of my image files from a directory. This code works perferctly everywhere i try. Except when i try within a wordpress theme:

    //path to directory to scan
    $directory = "http://mywebsite.com/imgs/";
    
    //get all image files with a .jpg extension.
    $images = glob($directory . "*.jpg");
    
    //print each file name
    foreach($images as $image)
    {
    echo $image;
    }

    I've tried modifying the code to display the directory dynamically, like so:

    $blogtheme = get_bloginfo('template_directory');
    $directory = $blogtheme . "/imgs/";

    and i can echo the $directory fine, but it doesn't return any of the files. If i echo $images i only get wordpress display the word 'Array' on my page.

    I think the problem is to do with this line, possibly the 'glob' function not working in wordpress:
    $images = glob($directory . "*.jpg");

    If anyone could provide any help, it would be much appreciated.

    Thanks!

  2. thame87
    Member
    Posted 7 months ago #

    Not sure if this is your problem but the glob only accepts paths and not urls.
    The php manual specificly notes it.

    Edit: nevermind this post. Misread the op.

    Btw can you var_dump the $images? If so what does it return?

  3. shovelshed
    Member
    Posted 7 months ago #

    I've typed in var_dump($images);

    I assume this is what you mean, and it returned this

    array(0) { }

  4. shovelshed
    Member
    Posted 7 months ago #

    I've managed to get it to work if instead of using the http url, entering this for the directory

    $directory = "wp-content/themes/mytheme/imgs/";

    is there a way to replace 'mytheme' with a bit of code to automatically pull the theme name in?

    cheers

  5. shovelshed
    Member
    Posted 7 months ago #

    No worries, i've solved it!

    I just added the following line
    $theme_name = get_template();
    and then changed the directory to
    $directory = "wp-content/themes/" . $theme_name . "/imgs/";

    Here's the final code:

    //path to directory to scan
    $theme_name = get_template();
    $directory = "wp-content/themes/" . $theme_name . "/imgs/";
    
    //get all image files with a .jpg extension.
    $images = glob($directory . "*.jpg");
    
    //print each file name
    foreach($images as $image)
    {
    echo $image;
    }

Reply

You must log in to post.

About this Topic