2013-05-02 82 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