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?

  • 1
    var_dump your variables and you should see where it goes wrong.
    – s_ha_dum
    Commented Jan 10, 2014 at 14:30

2 Answers 2


For wp_insert_attachment and wp_generate_attachment_metadata, change $file_name in the following way.

$file_name = $upload_dir['path'] . '/' . basename($file_name);

Wordpress codex for both function ( here and here ) says- ' Use absolute path and not the URI of the file. The file MUST be on the uploads directory' $_FILES['fileUpload'] just gives the name of the file , not the absolute path along with.


I did something similar a little while ago, and without rehashing everything line-by-line to remember how exactly I did what, the one thing that I spot different in my code vs. yours is you have:

$file_link = $file_post['url'];

whereas I have something like:

$file_link = $file_post['file'];

See if that makes the difference...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.