【问题标题】:Get files from a directory in random order using php (xampp)使用php(xampp)以随机顺序从目录中获取文件
【发布时间】:2013-04-26 09:07:42
【问题描述】:

我正在构建一个 wordpress 主题,我正在尝试使用 php 以随机顺序从目录中获取所有 jpg 文件...。 我在 win7 (localhost) 上使用 Xampp。

这是代码:

<? 
    $dir =  get_template_directory_uri().'/images/top/';

    $file_display = array ('jpg', 'jpeg');
    if(file_exists($dir) == false){
        echo 'Directory \'', $dir, '\' not found';
    } else {
       $dir_contents = scandir($dir);
       shuffle($dir_contents);
       foreach ($dir_contents as $file) {
           $file_type = strtolower(end(explode('.', $file)));
           if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true){ 
                echo '<img  src="', $dir, '/', $file, '" alt="', $file, '" />';    
           }
       }
   } 
?>

我总是得到

Directory 'http://localhost/ni/wp-content/themes/A/images/top/' not found 

我也尝试过改变

$dir =  get_template_directory_uri().'/images/top/';

到:

    $dir = "C:\xampp\htdocs\Ni\wp-content\themes\A\images\top\";

但仍然没有运气,任何帮助将不胜感激!

【问题讨论】:

  • (file_exists($dir) == false) 测试前面有没有和if
  • 是的,我编辑了这个问题,谢谢!我在我的原始代码上有它!
  • 尝试将get_template_directory_uri 替换为get_template_directory,因为get_template_directory_uri 提供了一个URI(而您不希望这样)
  • @EaterOfCorpses 自 PHP 5.0 起 file_exists 接受 HTTP(在其他一些协议中),因此只要 OP 使用 PHP5 就没有关系。
  • 使用 get_template_directory() 输出:C:\xampp\htdocs\Ni/wp-content/themes/A/images/top/ 带有混合斜杠(linux windows syle?),我得到目录''没找到

标签: php wordpress xampp wordpress-theming


【解决方案1】:

这就是我让它工作的方式。

  <? 
            $dir =  get_template_directory().'/images/top';
            $imageDir= get_template_directory_uri().'/images/top';
            $file_display = array ('jpg', 'jpeg');
            if (file_exists($dir) == false) {
              echo 'Directory \'', $dir, '\' not found';
            } else {
              $dir_contents = scandir($dir);
              shuffle($dir_contents);
              foreach ($dir_contents as $file) {
                $file_type = strtolower(end(explode('.', $file)));
                if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
                  echo '<img src="', $imageDir, '/', $file, '"  />';
                }
              }
            } 
  ?>

【讨论】:

  • 通过使用 get_template_directory() 来获取数组。和 get_template_directory_uri() 显示图像。谢谢大家帮助我解决这个问题......
  • 请注意,在大多数情况下,如果您尝试加载资源,最好使用get_stylesheet_directory() 而不是get_template_directory(),因为如果您使用的是子主题,前者将返回子主题的目录,而后者将返回父主题的目录,因此会导致您错过子主题资产。
猜你喜欢
  • 1970-01-01
  • 2012-06-30
  • 1970-01-01
  • 2012-09-21
  • 2016-03-02
  • 1970-01-01
  • 1970-01-01
  • 2013-12-19
  • 1970-01-01
相关资源
最近更新 更多