I want to add media_sideload_image
to upload a file programmatically . I've got it working when the image URL is online (e.g. http://etc...) but not when it's a local file from my hardrive or network drive (e.g. file://etc). I get the error Catchable fatal error: Object of class WP_Error could not be converted to string
.
Is this possible? I'm guessing there must be some way around it as the Wordpress admin site can upload local files.
I want to add media_sideload_image
to upload a file programmatically . I've got it working when the image URL is online (e.g. http://etc...) but not when it's a local file from my hardrive or network drive (e.g. file://etc). I get the error Catchable fatal error: Object of class WP_Error could not be converted to string
.
Is this possible? I'm guessing there must be some way around it as the Wordpress admin site can upload local files.
you can do this using the media_handle_upload() function. This is a working example that you can use as a guide for your requirements:
First Create your HTML form
<form method="post" id="uploadCartaAnno" enctype='multipart/form-data'>
<input class="text-input" name="carta_ano" type="file" id="carta_ano" multiple="false"/>
<?php wp_nonce_field( 'my_image_upload', 'my_image_upload_nonce' ); ?>
<input name="updatecarta_ano" type="submit" id="updatecarta_ano" class="hp-btn-file -icon-upload" value="Subir formato" />
<input name="action" type="hidden" id="action" value="update-user" />
</form>
Then your PHP code
if (
isset( $_POST['my_image_upload_nonce'] )
&& wp_verify_nonce( $_POST['my_image_upload_nonce'], 'my_image_upload' )
) {
// The nonce is valid and it is safe to continue.
// These files need to be included as dependencies when on the front end.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
// Let WordPress handle the upload.
$attachment_id = media_handle_upload( 'carta_ano', $comId );
if ( is_wp_error( $attachment_id ) ) {
// There was an error uploading the image.
} else {
// The image was uploaded successfully!
}
} else {
// Show some error message if nonce fails.
}
<form>
and the$_FILES
variable – karpstrucking Commented Feb 17, 2015 at 14:08