So I'm making a simple file uploader with wordpress where users don't need to go into wp-admin to add a file.
I have it working great, it uploads the file to the correct folder..etc but the only problem I'm running into is its returning the wrong file url.
For example when uploading a file it goes to '/wp-content/uploads/2014/01/file.png' but it returns the attachment URL as '/uploads/file.png'
My Code:
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);
Any idea what I'm doing wrong?
var_dump
your variables and you should see where it goes wrong.