2013-05-02 85 views
1

从目录中获取文件我建立一个wordpress主题,我试图从一个目录中使用php随机顺序获取所有的jpg文件.... 即时使用在win7(localhost)上的Xampp。从随机顺序使用php(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\"; 

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

+2

你是否在'(file_exists($ dir)== false)前有'if'前面的'test? – 2013-05-02 08:55:28

+0

是的,我编辑了这个问题,谢谢!我在我的原始代码上拥有它! – Firezilla12 2013-05-02 08:57:17

+0

尝试用'get_template_directory'替换'get_template_directory_uri',因为'get_template_directory_uri'提供了一个URI(并且你不想这么做) – EaterOfCode 2013-05-02 08:59:54

回答

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, '" />'; 
       } 
       } 
      } 
    ?> 
+0

通过使用get_template_directory()来获取数组。和get_template_directory_uri()来显示图像。 谢谢大家帮助我解决这个问题...... – Firezilla12 2013-05-02 09:21:46

+1

请注意,如果您尝试加载资产,在大多数情况下,最好使用'get_stylesheet_directory()'而不是'get_template_directory()',因为如果您使用子主题前者将返回子主题的目录,而后者将返回父主题的目录,并因此导致您错过子主题资产。 – ebohlman 2013-05-05 06:57:12

+0

好,有用.. – Vinith 2014-06-19 06:49:18