Here is what worked for me. Please note that I hard-coded the name of our images folder, rather than taking the time to create an options field where you could indicate the images folder input field [recommended]. You may need to modify that to match yours.
// new function to validate url for image to import
function woocommerce_osc_validate_url($url){
$ch = curl_init($url);
$opts = array(CURLOPT_RETURNTRANSFER => true, // do not output to browser
CURLOPT_URL => $url, // set URL
CURLOPT_NOBODY => true, // do a HEAD request only
CURLOPT_TIMEOUT => 5); // set timeout
curl_setopt_array($ch, $opts);
$retval = curl_exec($ch); // do it!
if ($retval !== FALSE){
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$retval = ($code == 200 ? TRUE : FALSE); // check if HTTP OK
curl_close($ch); // close handle
} // END IF
return $retval;
}
// modified the import_image function to use the CURL validator above
function woocommerce_osc_import_image($url){
$attach_id = 0;
$wp_upload_dir = wp_upload_dir();
$filename = $wp_upload_dir['path'].'/'.basename($url);
if(file_exists($filename)) $url = $filename;
// checking two folders because some fool stuffed some of our images in each
// first look in default /img/ folder.
$enc_url = rtrim($_POST['store_url'],'/').'/img/'.rawurlencode(basename($url));
// if not found, look in /images/ folder
if (woocommerce_osc_validate_url($enc_url)===FALSE)
$enc_url = rtrim($_POST['store_url'],'/').'/images/'.rawurlencode(basename($url));
// using CURL again, to copy file, for efficiency and to detect success/failure
$fp = fopen($filename,'w');
$ch = curl_init($enc_url);
curl_setopt($ch, CURLOPT_FILE, $fp);
$data = curl_exec($ch);
curl_close($ch);
fclose($fp);
// only create attachment information if the file copied successfully
if ( $data === TRUE){ // the file copied correctly
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
// Not sure why '37' but it is working, so I'll leave it...
$attach_id = wp_insert_attachment( $attachment, $filename, 37 );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
return $attach_id;
}
Hope this helps!