I am writing my first plugin to upload PDF files to a user specified directory other than the media directory specified in the Media menu under settings.

I need to extend the WP's native uploader so that files of a particular type in this case PDFs are uploaded to a different directory unlike images. In addition files uploaded in this user defined directory should be viewable in the native upload/insert window whenever the need arises to insert them into a page or a post.

Is it possible to extend WP's native uploader through a plugin or would I have to design my own uploader? This seems to be overkill for just one type of file considering that there is already an excellent uploader available.

I do not think that delving into WP's code and changing it is an option.

Thanks in advance.

1 Answer 1


Both of these are possible.

Insert Attachment into Media Library

By using the wp_insert_attachment function, you can insert your uploaded images to the Media Library.

This is the example code from the Docs:

  $wp_filetype = wp_check_filetype(basename($filename), null );
  $wp_upload_dir = wp_upload_dir();
  $attachment = array(
     'guid' => $wp_upload_dir['baseurl'] . _wp_relative_upload_path( $filename ), 
     'post_mime_type' => $wp_filetype['type'],
     'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
     'post_content' => '',
     'post_status' => 'inherit'
  $attach_id = wp_insert_attachment( $attachment, $filename, 37 );
  // you must first include the image.php file
  // for the function wp_generate_attachment_metadata() to work
  require_once(ABSPATH . 'wp-admin/includes/image.php');
  $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
  wp_update_attachment_metadata( $attach_id, $attach_data );

Change Directory of Uploads

To change the directory of your uploads, you need to use the upload_dir filter. Yoast has a pretty good tutorial on how to do such.

add_filter('upload_dir', 'my_upload_dir');
$upload = wp_upload_dir();
remove_filter('upload_dir', 'my_upload_dir');

function my_upload_dir($upload) {
    $upload['subdir']   = '/sub-dir-to-use' . $upload['subdir'];
    $upload['path']     = $upload['basedir'] . $upload['subdir'];
    $upload['url']      = $upload['baseurl'] . $upload['subdir'];
    return $upload;
  • Thanks this answer's my question I think the example code above would help me write the plugin. :-)
    – nandac
    Mar 1, 2012 at 12:49

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.