1

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.

2
  • files uploaded via the admin are done using a <form> and the $_FILES variable – karpstrucking Feb 17 '15 at 14:08
  • Image can not be uploaded with folder path, they can be uploaded if you can move them on a url like localhost/images – Vikram Apr 14 '15 at 13:17
0

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.
                      }
1
  • doesn't seem to actually answer the question – Mark Kaplun Jul 9 at 5:01

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.