Having Issues on Using PHP glob() in WordPress

You should use paths with glob, not URLs.

But src attributes needs URLs.

So something like this should work:

$base_dir = trailingslashit(get_template_directory());
$dir="img/services/";
$images   = glob($base_dir.$dir.'*.png');

foreach($images as $image) {
    $url = get_theme_file_uri($dir.basename($image));
    printf('<div class="dynamic item"><img src="https://wordpress.stackexchange.com/questions/288995/%s" alt=""></div>', esc_url($url));
}

Where I make use of:

  • get_template_directory To obtain the root path of (parent) theme
  • basename to obtain just the file name of the current image file path
  • get_theme_file_uri to obtain the full URL of the image, in a child-theme friendly way: if the image is found in child theme it will be used from there, otherwise will be used from parent theme.

Leave a Comment