前端文件上传返回错误的附件网址

时间:2014-01-10 14:29:33

标签: php wordpress file-upload

所以我正在使用wordpress创建一个简单的文件上传器,用户无需进入wp-admin添加文件。

我工作得很好,它将文件上传到正确的文件夹..但是我遇到的唯一问题是它返回了错误的文件网址。

例如,在上传文件时,它会转到'/wp-content/uploads/2014/01/file.png',但它会将附件网址返回为'/uploads/file.png'

我的代码:

define('WP_USE_THEMES', false);
require_once($_SERVER['DOCUMENT_ROOT']. '/wp-load.php');
include_once($_SERVER['DOCUMENT_ROOT']. '/wp-admin/includes/media.php');
include_once($_SERVER['DOCUMENT_ROOT']. '/wp-admin/includes/file.php');
include_once($_SERVER['DOCUMENT_ROOT']. '/wp-admin/includes/image.php');

 if(!$_FILES) exit;
 if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");

//define variables
 if(isset($_FILES['fileUpload'])) 
     {
     $files = $_FILES['fileUpload'];
     }
 $upload_dir = wp_upload_dir();

 $file_name = $files['name'];
 $file_vars = array('test_form' => FALSE); //Allows form submission
 $file_post = wp_handle_upload($files, $file_vars); //Posts File
 $file_link = $file_post['url']; //Full URL
 $file_type = wp_check_filetype(basename($file_link), null); //File Extension

 $post_name = preg_replace('/\.[^.]+$/', '', basename($file_link)); //Post Name

 $attachment = array(
            'guid' => $file_link, 
            'post_mime_type' => $file_type['type'],
            'post_title' => $post_name,
            'post_content' => '',
            'post_status' => 'inherit'
                );
 $attach_id = wp_insert_attachment($attachment, $file_name);
 //Generates meta
 $attach_data = wp_generate_attachment_metadata($attach_id, $file_name);
 //Updates meta
 $attach_final = wp_update_attachment_metadata($attach_id, $attach_data);

知道我做错了吗?

1 个答案:

答案 0 :(得分:0)

我已经弄清楚我做错了什么!

基本上在生成附件元数据时,我给它提供了错误的路径..

我正在给它实际文件的路径'/ wp-content / uploads / 2014/01 / file.png'

但实际上它需要文件夹的路径'/ wp-content / uploads / 2014/01 /