2011-03-17 69 views
0

試圖在Wordpress中設置一個上傳MIME的循環。我有一個帶逗號分隔列表(option_file_types)的CMS選項,用戶可以在其中指定可以上傳的文件類型列表。但我無法弄清楚如何讓它們全部放入foreach並正確輸出。當不在foreach中時,它可以處理一個文件類型條目。任何幫助將非常感激。Foreach Loop for Wordpress上傳mimes

代碼:

function custom_upload_mimes ($existing_mimes = array()) { 

$file_types = get_option('option_file_types'); 
$array = $file_types; 
$variables = explode(", ", $array); 

foreach($variables as $value) { 
    $existing_mimes[''.$value.''] = 'mime/type']); 
} 

return $existing_mimes; 
} 

預期輸出:

$existing_mimes['type'] = 'mime/type'; 
$existing_mimes['type'] = 'mime/type'; 
$existing_mimes['type'] = 'mime/type'; 
+0

你能發佈的'$ file_types'值和預期輸出的價值?另外,你現在得到什麼輸出? – Dogbert 2011-03-17 16:59:21

+0

當你回顯'$ file_types'時,你只需要得到逗號分隔的列表..所以基本的文件類型:'pdf,doc,docx,xl​​s,xlsx'。現在,它不輸出任何東西 – 2011-03-17 17:05:37

回答

2
function custom_upload_mimes ($existing_mimes = array()) { 
    $file_types = get_option('option_file_types'); 
    $variables = explode(',', $file_types); 

    foreach($variables as $value) { 
     $value = trim($value); 
     $existing_mimes[$value] = $value; 
    } 

    return $existing_mimes; 
} 

如果您$file_types不包含MIME類型,但是文件擴展名的意見建議,那麼你還需要將文件轉換擴展到MIME類型。類如this one將幫助您將擴展轉換爲適當的MIME類型。

例如:

require_once 'mimetype.php'; // http://www.phpclasses.org/browse/file/2743.html 
function custom_upload_mimes ($existing_mimes = array()) { 
    $mimetype = new mimetype(); 
    $file_types = get_option('option_file_types'); 
    $variables = explode(',', $file_types); 

    foreach($variables as $value) { 
     $value = trim($value); 
     if(!strstr($value, '/')) { 
      // if there is no forward slash then this is not a proper 
      // mime type so we should attempt to find the mime type 
      // from the extension (eg. xlsx, doc, pdf) 
      $mime = $mimetype->privFindType($value); 
     } else { 
      $mime = $value; 
     } 
     $existing_mimes[$value] = $mime; 
    } 

    return $existing_mimes; 
} 
+0

Presto!非常好的答案Treffynnon。謝謝你,先生! – 2011-03-17 17:24:52