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...
wp_handle_uploadis the wrong approach. Because it handles non local files. From the Wordpress doc: '$file Reference to a single element of $_FILES.' - S.Visser