dqrm8199 2017-02-03 18:42
浏览 70
已采纳

Wordpress:使用glob()返回一个空数组

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条回答 默认 最新

  • dongtan7639 2017-02-04 03:01
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解