2011-03-17 64 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