Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer

up vote 4 down vote accepted

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:

<?php
  $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;
}
share|improve this answer
    
Thanks this answer's my question I think the example code above would help me write the plugin. :-) –  navanitachora Mar 1 '12 at 12:49
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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