1
votes

I am working on a script to upload data to a create a post with an (already uploaded) file attached. The file is located in the wp-content/uploads folder, but not added to the media gallery.

How could I use Wordpress functions to take the file (for example, in wp-content/uploads/files-from-form/123.pdf) and add this to a post ID?

So far I’ve tried this code, but it’s not working…

$uploadedfile = $_SERVER['DOCUMENT_ROOT']."/wp-content/uploads/files-from-form/123.pdf";

$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile ) {
    //file is uploaded successfully. do next steps here.
        var_dump($movefile);

} else {
    echo 'Failed';
}

This returns the error:

array(1) { ["error"]=> string(1) "/" }

Any help greatly appreciated...

1
wp_handle_upload is the wrong approach. Because it handles non local files. From the Wordpress doc: '$file Reference to a single element of $_FILES.' - S.Visser
Probably this plugin will help you: wordpress.org/extend/plugins/add-from-server - S.Visser
Thanks @S.Visser Do you know what I should use instead? Or could I load the uploaded file into the $_FILES array somehow?? - user2761030
Thanks for the plug-in link - I need to be able to add a file programmatically though, and the add-from-server plugin would require the user to log in and press a button to add a file to the media gallery... - user2761030
Depending on the rest of your code, consider codex.wordpress.org/Function_Reference/wp_insert_attachment - emsoff

1 Answers

1
votes

Provided you have the ID of the parent post you can use wp_insert_attachment