WordPress Invalid image URL when using media_sideload_image

I am using the wordpress function media_sideload_image to upload images from an external link like below:

   $url = 'http://pinnaclepublic.pinewoodsa.co.za/vehicles/plugins/ViewImage.aspx?guid=F92A44F3-71AC-4B2C-8BC4-8CC53578B722&VehicleId=101887&ImageNumber=1&Size=3';
   $post_id = 101;

   media_sideload_image ($url,$post_id);

But I get the error:

Read More
WP_Error Object
(
    [errors] => Array
        (
            [image_sideload_failed] => Array
                (
                    [0] => Invalid image URL
                )

        )

    [error_data] => Array
        (
        )

)

Question:
How can I make media_sideload_image, work properly with this particular url which I cannot change.

Related posts

2 comments

  1. Problem:

    Its a problem with the URL. The file module of WordPress can’t recognize any file extension from the URL you’re giving it. And hence throws this error.
    Have a look at the source code of this function https://developer.wordpress.org/reference/functions/media_sideload_image/

    Solution:

    I was facing this problem for the past hour. After severe headache, I was able to use a hack around it.

    All you got to do is append some random Query Param at the end of the
    URL that equals to the “.jpeg” or “.png”.

    Example:

    $url = 'http://pinnaclepublic.pinewoodsa.co.za/vehicles/plugins/ViewImage.aspx?guid=F92A44F3-71AC-4B2C-8BC4-8CC53578B722&VehicleId=101887&ImageNumber=1&Size=3';
    $url_with_pseudo_extension = $url . '?ext=.jpeg'
    

    This will let the URL walk out safely from the file module without throwing any errors.

  2. If you’re using this function outside the context of /wp-admin
    you need to include media.php and depending includes.

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

    See the notes for the documentation of media_sideload_image()

    You can also create your own function like this answer

Comments are closed.