Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
941 views
in Technique[技术] by (71.8m points)

wordpress - Read images from a directory using PHP

I am wanting to find out if the following is possible with PHP inside WordPress.

Basically if I have a directory in my site called "promos" that consists of 1 to many images (as these images can change), that I would like to read from within a PHP file into a carousel setup, i.e. something similar to this:

   <div class="scrollable" id="browsable">   

   <div class="items"> 

          <?php 
            $tot_images_from_promo_dir = [get_total_image_count_in_promos_dir]; 

            for ( $counter = 1; $counter <= $tot_images_from_promo_dir; $counter ++) {
                echo "<div>";
                    echo "<a href="#"><img src="[image_from_promo_directory]" /></a>
                echo "</div>";
            }
          ?>
    </div>
</div>

Basically want to somehow with php read total amount of images in my promo directory and then use this total in my loop max value and read each image file name in the promo directory and pass into my <img src=[image_name_from_promo_dir].

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming that all files in the promos directory are images:

<div class="scrollable" id="browsable">   
   <div class="items"> 
      <?php 
        if ($handle = opendir('./promos/')) {

            while (false !== ($file = readdir($handle))) {
                echo "<div>";
                    echo "<a href='#'><img src='".$file."' /></a>";
                echo "</div>";
            }
            closedir($handle);
        }
      ?>
    </div>
</div>

If, however, there are files in the directory that are not images, you would need to check that before showing it. The while loop would need to change to something like:

while (false !== ($file = readdir($handle))) {
    if ((strpos($file, ".jpg")) || (strpos($file, ".gif"))) {
        echo "<div>";
            echo "<a href='#'><img src='".$file."' /></a>";
        echo "</div>";
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...