skip to Main Content

I’m trying to loop througt all images of a certain folder with the following script:

function loopImages(){
            $imagePath = bloginfo('template_url') . '/assets/images/' . 'casa_intera';
            echo $imagePath;
            $fileList = list_files( $imagePath, 2 );
            foreach ( $fileList as $file ) {
              echo '<img src="' . $imagePath . $file . '" alt="" data-fancybox="gallery" loading="lazy">';
            }
          }
          loopImages();

It only echoes the $imagePathas http://localhost:8888/wordpress/wp-content/themes/casale-wp/assets/images/casa_intera which is correct, but doesn’t output the rest.

Thanks

EDIT
currently I have this code:

function loopImages(){
            $imagePath = bloginfo('template_url') . '/assets/images/' . 'casa_intera';
            $fileList = list_files( $imagePath, 2 );
            foreach ( $fileList as $file ) {
              var_dump( $file );
            }
          }
          loopImages();

But I only get this back as an HTML item

" http://localhost:8888/wordpress/wp-content/themes/casale-wp"

2

Answers


  1. Chosen as BEST ANSWER

    At the end I went with this solution.

    function loopImages(){
                $imagePath = get_template_directory() . '/your/images/directory/';
                $basePath = get_template_directory_uri(); . '/your/images/directory/';
                $imageList = scandir( $imagePath );
                foreach( $imageList as $image ){
                  echo '<img src="' . $basePath . $image . '" alt="" data-fancybox="gallery" loading="lazy">';
                }
              }
              loopImages();
    

  2. Here is an option using glob to get all jpeg files in a directory. The list_files function is an admin function and will not work on the front end.

    <?php
    function loopImages() {
        $image_directory  = '/assets/images/casa_intera/';
        $image_path       = get_stylesheet_directory() . $image_directory . '*.jpg'; // get all jpeg files.
        $file_list        = glob( $image_path );
        foreach ( $file_list as $file ) {
            echo '<img src="' . esc_url( get_stylesheet_directory_uri() . $image_directory . basename( $file ) ) . '" alt="" data-fancybox="gallery" loading="lazy">';
        }
    }
    loopImages();
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search