Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress media_sideload_image - Download http://placekitten.com/100/100?

media_sideload_image

WordPress have a function called media_sideload_image. It is used to upload an image and attach it to the media library.

I accepts image urls like this:

h**p://s.wordpress.org/style/images/wp-header-logo.png

Rewritten URLs

Some URLs on the web are rewritten, for example:

http://placekitten.com/100/100

Error message:

"Sorry, this file type is not permitted for security reasons."

The file type is a correct JPG-file but the file extension is missing.

Adding extra MIME types don't work, in my case

I tried this function but it does not help me, because it's the file extension that is not set.

add_filter('upload_mimes', 'add_custom_upload_mimes');
function add_custom_upload_mimes($existing_mimes){
    $existing_mimes['jpeg'] = 'image/jpeg';
    return $existing_mimes;
}

Question

How do I upload the URL h**p://placekitten.com/100/100 with media_sideload_image or alike to attach the image to the media library?

like image 903
Jens Törnell Avatar asked Dec 07 '22 10:12

Jens Törnell


1 Answers

I read your question yesterday, when i need this solution. I find a answer after 24 hours.

Here is Full solution

require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');

$image_url = "http://domain.com/blog/23092839823";
$image_tmp = download_url($image_url);

    if( is_wp_error( $image_tmp ) ){
        echo "<br> Image Download Fail:";
    }else {
        $image_size = filesize($image_tmp);
        $image_name = basename($image_url) . ".jpg"; // .jpg optional


        //Download complete now upload in your project
        $file = array(
           'name' => $image_name, // ex: wp-header-logo.png
           'type' => 'image/jpg',
           'tmp_name' => $image_tmp,
           'error' => 0,
           'size' => $image_size
        );


        //This image/file will show on media page...
        $thumb_id = media_handle_sideload( $file, $post_id, $desc);
        set_post_thumbnail($post_id, $thumb_id); //optional

        echo "<br> Image Save ";
    }
like image 193
asad raza Avatar answered Mar 16 '23 21:03

asad raza