Search code examples
woocommercewoocommerce-rest-api

Woocommerce API thinking image SRC is a different type of file, not a JPG


Example:

  ["images"]=>
  array(6) {
    [0]=>
    array(2) {
      ["src"]=>
      string(112) "https://nz.tradevine.com/BlobStorage/GetFullPhoto?photoID=3783754511503592459&organisationID=3468490059683634443"
      ["position"]=>
      string(1) "0"
    }

The image is https://nz.tradevine.com/BlobStorage/GetFullPhoto?photoID=3783754511503592459&organisationID=3468490059683634443

I get an error: "Error: Invalid image: Sorry, you are not allowed to upload this file type. [woocommerce_api_product_image_upload_error]

I change WP_config file to allow any type of file upload.

define('ALLOW_UNFILTERED_UPLOADS', true);

it trys to upload a file called: GetFullPhoto no .jpg

and it does not work.

This ust to work fine.

Any ideas?


Solution

  • Because the url doesn't include a file extension in it's name, Wordpress treats it as a file with no extension thus failing the wp_check_filetype_and_ext test.

    You can add a filter to add .jpg to the end of a filename if it has no extension and is in fact a jpeg like so

    add_filter('wp_handle_sideload_prefilter', 'add_jpg_if_no_extension');
    
    function add_jpg_if_no_extension($file){
        if(!pathinfo($file['name'], PATHINFO_EXTENSION) && mime_content_type($file['tmp_name']) == 'image/jpeg'){
            $file['name'] .= '.jpg';
        }
        return $file;
    }
    

    EDIT: A more complete solution to work for all image types

    add_filter('wp_handle_sideload_prefilter', 'add_extension_if_none_exists');
    
    function add_extension_if_none_exists($file){
        if ( pathinfo( $file['name'], PATHINFO_EXTENSION ) ) {
            return $file;
        }
        $real_mime = wp_get_image_mime( $file['tmp_name'] );
        $mime_to_ext = apply_filters(
            'getimagesize_mimes_to_exts',
            array(
                'image/jpeg' => 'jpg',
                'image/png'  => 'png',
                'image/gif'  => 'gif',
                'image/bmp'  => 'bmp',
                'image/tiff' => 'tif',
                'image/webp' => 'webp',
            )
        );
        if ( ! empty( $mime_to_ext[ $real_mime ] ) ) {
            $file['name'] .= '.' . $mime_to_ext[ $real_mime ];
        }
        return $file;
    }