Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function importImageByFilenames() {
- $logFile = Mage::getBaseDir('media') . "/sku_import.log";
- $mediaApi = Mage::getModel("catalog/product_attribute_media_api");
- $importPath = Mage::getBaseDir('media') . "/importproducts/images/";
- $catalogPath = Mage::getBaseDir('media') . "/catalog/product";
- $skus = array();
- $linked = array();
- $files = scandir($importPath);
- foreach ($files as $file) {
- $re = '/(?<sku>.*?)(-|\.|_)(?<index>\d)?/';
- preg_match($re, $file, $matches);
- if(empty($matches['sku'])) continue;
- $index = empty($matches['index']) ? 1 : (int) $matches['index'];
- $image = array(
- 'fileName' => $file,
- 'index' => $index
- );
- $skus[] = $matches['sku'];
- $linked[$matches['sku']][] = $image;
- }
- $uniqueSkus = array_unique($skus);
- $_products = Mage::getResourceModel('reports/product_collection')->addAttributeToSelect('*')
- ->addFieldToFilter('sku',array('in'=>$uniqueSkus));
- // $existSkus = array();
- foreach ($_products as $_p) {
- $_product = Mage::getModel('catalog/product')->load($_p->getId());
- $gallery = $_product->getMediaGallery();
- if (!empty($gallery['images'])) {
- // need to remove if not empty
- // foreach ($gallery['images'] as $img) {
- // if ($img['position'] == 1) {
- // $_product->setImage($img['file']);
- // $_product->setSmallImage($img['file']);
- // $_product->setThumbnail($img['file']);
- // $_product->save();
- // echo "set as default {$img['file']} \n";
- // }
- // print_r($img);
- // $ph = $catalogPath.''.$img['file'];
- // if (!file_exists($ph)) {
- // $mediaApi->remove($_p->getId(), $img['file']);
- // echo "removed {$img['file']} \n";
- // }
- }
- } else {
- //add image
- //echo "{$_p->getSku()}\n";
- // foreach ($linked[$_p->getSku()] as $item) {
- // $pathToFile = $importPath .''. $item['fileName'];
- // $media_attr = null;
- // if ($item['index'] == 1) $media_attr = array('image', 'small_image', 'thumbnail');
- //
- // if(file_exists($pathToFile)) {
- // $_product->addImageToMediaGallery ($pathToFile, $media_attr, false, false);
- // $msg = "Sku: {$_p->getSku()}Image {$item['fileName']} added \n";
- // echo $msg;
- // file_put_contents($logFile,$msg,FILE_APPEND);
- // }
- //
- // }
- // try {
- // $_product->save();
- //
- // } catch (Exception $e) {
- // $msg = "Sku: {$_p->getSku()}Image $e \n";
- // echo $msg;
- // file_put_contents($logFile,$msg,FILE_APPEND);
- // }
- }
- // $existSkus[] = $_product->getSku();
- }
- // $diff = array_diff($uniqueSkus,$existSkus);
- // print_r(count($_products));
- // print_r(count($linked));
- // print_r(count($uniqueSkus));
- // print_r($diff);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement