Search code examples
phpjquerywordpresscycleglob

PHP glob() breaks on WordPress sub pages


I've been struggling with this for a while now.

I've got an image gallery running using jQuery cycle plugin and the files are pulled from a folder using PHP glob(). Problem is, when I navigate to another page the gallery breaks due to the url of the new page being tacked on at the beginning of the file path.

Example:

Front Page url: http://localhost/project/image-display-images/image.jpg

Other Page url: http://localhost/**NEWPAGE**/project/image-display-images/image.jpg

Here's my code:

$files = glob('image-display-images/*.*');

       for ($i=1; $i<count($files); $i++)

       {
          $num = $files[$i];
          echo '<img src="'.$num.'"'.' alt="Campus Images" width="362" height="246"/>';
       }

This would generate a list of images for jQuery cycle to scroll through. It only works on the front page though.

Any ideas?

SOLVED!

Here is my new code:

$files = glob(ABSPATH.'/image-display-images/*.*');

foreach ($files as $f) {
    echo '<image src="'.home_url(str_replace(ABSPATH,'',$f)).'"alt="Campus Images" width="362" height="246"/>';

}

This works on all pages.

Thank you!


Solution

  • Use an absolute path:

    $files = glob(ABSPATH.'image-display-images/*.*');
    

    The WordPress Core sets the ABSPATH constant so it should be fairly reliable.

    glob deals with filesystem paths, but you are trying to load URLs. To display the files the way you are trying to, you will need to convert the results to URLs. Here is a bare-bones example.

    $files = glob(ABSPATH."*.*");
    foreach ($files as $f) {
      echo home_url(str_replace(ABSPATH,'',$f));
    }
    

    You may better off writing you own function to grab your file names, rather than depending on glob which does come with a warning about not being available on some systems. See: http://codex.wordpress.org/Filesystem_API