我使用以下代码将我的Wordpress网站上的所有PDF上传内容移动到特定文件夹
// Function to move PDF Uploads to specific folder
<?php
add_filter('wp_handle_upload_prefilter', 'wpse47415_pre_upload');
add_filter('wp_handle_upload', 'wpse47415_post_upload');
function wpse47415_pre_upload($file){
add_filter('upload_dir', 'wpse47415_custom_upload_dir');
return $file;
}
function wpse47415_post_upload($fileinfo){
remove_filter('upload_dir', 'wpse47415_custom_upload_dir');
return $fileinfo;
}
function wpse47415_custom_upload_dir($path){
$extension = substr(strrchr($_POST['name'], '.'), 1);
if (!empty($path['error']) || $extension != 'pdf') {
return $path;
} //error or other filetype; do nothing.
$customdir = '/pdf';
$path['path'] = str_replace($path['subdir'], '', $path['path']); //remove default subdir (year/month)
$path['url'] = str_replace($path['subdir'], '', $path['url']);
$path['subdir'] = $customdir;
$path['path'] .= $customdir;
$path['url'] .= $customdir;
return $path;
}
?>
我想对DOCX和XLS文件使用相同的代码,但如果我重复代码Wordpress失败,我该怎么做才能将此代码重用于不同的文件类型
答案 0 :(得分:1)
只需在您的函数中考虑这些不同的文件类型:
function wpse47415_custom_upload_dir($path){
$allowed_extensions = array('pdf', 'docx', 'xls');
$extension = substr(strrchr($_POST['name'],'.'),1);
// On error or other filetyp, do nothing
if( !empty($path['error']) || !in_array($extension, $allowed_extensions) ) {
return $path;
}
$customdir = '/' . $extension; // dynamically generate the custom directory
$path['path'] = str_replace($path['subdir'], '', $path['path']); //remove default subdir (year/month)
$path['url'] = str_replace($path['subdir'], '', $path['url']);
$path['subdir'] = $customdir;
$path['path'] .= $customdir;
$path['url'] .= $customdir;
return $path;
}
如果您需要多个扩展程序才能进入同一目录,则可以使用switch
statement。