4

I'm using my own upload.php file to upload images to:

$upload_dir = wp_upload_dir();
$targetDir = $upload_dir['path'].'/';

It works like it should with this exception that images uploaded to uploads/2012/08/ don't appear in Media Library. Is there any function to "register" them there and in WP's database?

6

It's because you're not registering them as a media type. Every upload is a WordPress post of the attachment type.

To start, it would be something like this:

$file_name = 'Some Name';
$file_path = '/path/to/uploads/2012/08/04/newfile.jpg';
$file_url = 'http://url/to/uploads/2012/08/04/newfile.jpg';
$wp_filetype = wp_check_filetype($file, null);
$attachment = array(
    'guid'           => $file_url,
    'post_mime_type' => $wp_filetype['type'],
    'post_title'     => $file_name,
    'post_status'    => 'inherit',
    'post_date'      => date('Y-m-d H:i:s')
);
$attachment_id = wp_insert_attachment($attachment, $file_path);
$attachment_data = wp_generate_attachment_metadata($attachment_id, $file_path);
wp_update_attachment_metadata($attachment_id, $attachment_data);

That should create an entry in your Media panel, and also convert the image to all the sizes you're using in your theme.

A good option for you is to insert the above procedure in your upload.php. For that, you would need to include the WordPress required files too. Otherwise you would have to tell WordPress to run this somehow, maybe by a $_REQUEST query or by a cron job.

  • Great! That's what I was looking for! Thanks! I'm including wp-load.php already. – Paul Aug 4 '12 at 13:32
  • Just checking, great answer, but what is the significance of that '$file_name' please, is that simply the post to which the images will be attached? Or an unfortunately-named default for some variable necessary for the upload process? – Hektor Jul 10 at 18:16
0

I think you should start digging in media_handle_upload function. It's description in codex vague so try to understand it's code.

You can use this function to handle even uploads for you or you can grab some parts of it's code to integrate in your own.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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