0

I am trying to pull all images from a specified directory and then display them. I used the below piece of code in a regular website and it works

<?php $dirname = "images/tile/tile2/";
  $images = glob($dirname."*.jpg");

  foreach($images as $image) {
  echo '<li><img src="'.$image.'" /><br /></li>';
}?>

I have now moved this code and modified it to a wordpress site and I get an empty array.

<?php $dirname = get_template_directory_uri()."/images/tile/tile1/";
      $images = glob($dirname. "*.jpg"); 
      //$images = glob($dirname."*. {jpg}", GLOB_BRACE); - tried with GLOB_RACE
      foreach($images as $image) {
        echo '<li><img src="'.$image.'" /><br /></li>';
}?>

Second code

<?php define('ACCREDPATH', get_template_directory_uri() . '/images/tile/tile1/');
 $images = glob(ACCREDPATH. "*.jpg");
 //$images = glob(ACCREDPATH. "*. {jpg}", GLOB_BRACE); - tried with GLOB_RACE 
foreach($images as $image) {
   echo '<li><img src="'.$image.'" /><br /></li>';
}?>
  • I have checked that the images are in the folder
  • I have done a var_dump and I am getting the right path.
  • var_dump on the glob($images) gives array(0){ }
  • I have also looked for other threads with this issue and still nothing

Please any help would be useful.

1 Answer 1

2

glob works on a local path rather than a URL. The function needs to be able to access the server's filesystem which it can't do remotely (via URL).

http://php.net/manual/en/function.glob.php

The path you're providing in your working code is relative. It functions because it can be used as both a file path and a URL.

To achieve the same result with an absolute path to your theme you'll need to use get_template_directory(). In the example provided I'm using get_template_directory() to get the absolute path and get_template_directory_uri() to output as a URL.

Example:

$theme_img_path = '/images/tile/tile1/';
$images  = glob( get_template_directory() . $theme_img_path . '*.jpg' );

foreach ( $images as $image ) {

    // Convert the filename into an absolute URL.
    echo get_template_directory_uri() . $theme_img_path . basename( $image );
}

There's another issue in your second attempt that's worth pointing out. You can't use a function to set the value of a constant.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.