I am using this code to try to upload images located in my server to Media Library of my wordpress installation.
<?php
include("../../../wp-blog-header.php");
include("../../../wp-admin/includes/file.php");
include("../../../wp-admin/includes/media.php");
$id = 0;
$image = $_SERVER['DOCUMENT_ROOT'] . "/image01.jpg";
$array = array( //array to mimic $_FILES
'name' => basename($image), //isolates and outputs the file name from its absolute path
'type' => 'image/jpeg', //yes, thats sloppy, see my text further down on this topic
'tmp_name' => $image, //this field passes the actual path to the image
'error' => 0, //normally, this is used to store an error, should the upload fail. but since this isnt actually an instance of $_FILES we can default it to zero here
'size' => filesize($image) //returns image filesize in bytes
);
media_handle_sideload($array, $id); //the actual image processing, that is, move to upload directory, generate thumbnails and image sizes and writing into the database happens here
?>
I can see that this code takes my image called “image01.jpg” located in that path and then it put the image to /wp-contents/uploads/. However when I go to the admin panel in wordpress to see the image in the Media Library I cannot see the image. Also there is not any row in the wp_posts of this image.
UPDATE:
I used this time this code:
$result = media_handle_sideload($array, $id);
echo "Finish media handle sideload<br>";
if ( ! is_wp_error( $result ) ) {
echo "Result<br>";
print_r($result);
} else {
echo "Error<br>";
print_r($results);
}
echo "Finish script<br>";
Nothing is shown is the execution. I can’t see the msg “Finish media handle sideload”. However the file is moved from path specified in “$image” to “wp-content/uploads”. Note that the files is moved, not copied, so if I execute the script without copy again the image to the source (path of $image), I can see some warnings about filesize function likes this:
Warning: filesize(): stat failed for
C:/Users/dlopez/Documents/Development/web-folders/image01.jpg in
C:UsersdlopezDocumentsDevelopmentweb-folderswp_testwp-contentpluginspods-csv-importerupload.php
on line 16
Your failing and getting a WP_Error object returned before the function runs wp_insert_attachment().
You should always include a check for
is_wp_error( $thing )
when calling a function that returns WP_Errors.Your problem will be listed in the output of error messages
apply this code and pass your file URL. That is works for me.
for more details please check WordPress function reference for media_handle_sideload.
You shouldn’t assign a string valus to
image
. According to the example in this page, at first you must download files to temporary directory usingdownload_url()
and assign object returned by this function to$image
:Don’t forget to
unlink()
the$image
at the end of function.Does the form that the file is coming from use:
e.g.,