下面的PHP代码允许用户在WordPress前端上传文件。我搜索了几个小时,但无法显示上传文件的URL。
我输入索引。php
<?php
if ( isset( $_POST[\'upload_attachments\'] ) && $_SERVER[\'REQUEST_METHOD\'] === \'POST\' && wp_verify_nonce($_POST[\'secure_upload\'], \'upload_attachments_nonce\')) {
//checking if upload is empty
//checking if universal filesize is valid
if ($_FILES) { //loop through multiple files.
$files = $_FILES[\'upload\'];
foreach ($files[\'name\'] as $key => $value) {
if ($files[\'name\'][$key]) {
$file = array(
\'name\' => $files[\'name\'][$key],
\'type\' => $files[\'type\'][$key],
\'tmp_name\' => $files[\'tmp_name\'][$key],
\'error\' => $files[\'error\'][$key],
\'size\' => $files[\'size\'][$key]
);
$uploaded_file_type = $files[\'type\'][$key];
$allowed_file_types = array(\'application/x-zip-compressed\', \'image/jpg\', \'image/jpeg\', \'image/png\', \'application/pdf\', \'application/zip\', \'video/mp4\');
$uploaded_file_size = $files[\'size\'][$key];
$size_in_kb = $uploaded_file_size / 1024;
$file_size_limit = 10000; // Your Filesize in KB
if(in_array($uploaded_file_type, $allowed_file_types)) {
if( $size_in_kb > $file_size_limit ) {
$upload_error .= \'Image files must be smaller than \'.$file_size_limit.\'KB\';
return;
} else {
$_FILES = array("upload" => $file);
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$post_id);
//return; this loop neds to run multiple times so no return here
}
}
} else { $upload_error .= \'Invalid File type\';
return;
}
}
}
}
header (\'Location: \' . $_SERVER[\'REQUEST_URI\']);//Post, redirect and get
exit();
}//end of nonce check ?>
这就是函数。php function insert_attachment($file_handler,$post_id,$setthumb=\'false\') {
// check to make sure its a successful upload
if ($_FILES[$file_handler][\'error\'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . \'/includes/image.php\');
require_once(ABSPATH . "wp-admin" . \'/includes/file.php\');
require_once(ABSPATH . "wp-admin" . \'/includes/media.php\');
$attach_id = media_handle_upload( $file_handler, $post_id );
//if ($setthumb) update_post_meta($post_id,\'_thumbnail_id\',$attach_id);
return $attach_id;
}
附加问题此代码不允许上载rar文件它只上载zip文件,是否也可以上载rar文件?提前感谢