2017-06-06 76 views
0

我需要用新的產品圖像替換產品圖像。
我需要用新圖像替換位置2中的圖像。
這是我的代碼。
如何更換Magento中的產品圖像?

$position = 2;//this is the image to delete 
$file_location = "../WS-Access-000036-Black-2.jpg"; 
$sku = "WS-Access-000036-Black"; 



//delete image 
$mediaApi = Mage::getModel("catalog/product_attribute_media_api"); 
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku); 
$product_id = $product->getId(); 
$items = $mediaApi->items($product_id); 
foreach($items as $item){ 
    if($item['position']=="$position" or ($position==1 and $item['position']=="0")){ 

     $mediaApi->remove($product_id, $item['file']);//this doesnt remove file from directory 

     $image_location = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'product' . $item['file']; 
     unlink ($image_location);//have to use this to delete image from disk because $mediaApi->remove doesn't delete it from disk 
     break; 
    } 
} 
//end delete image 
//EVERYTHING UP TO HERE WORKS, THE IMAGE IS DELETED FROM THE DISK AND 
//IN THE BACKEND OF THE PRODUCT 




//save new image 
$pathInfo = pathinfo($file_location); 
switch($pathInfo['extension']){ 
    case 'png': 
     $mimeType = 'image/png'; 
     break; 
    case 'jpg': 
     $mimeType = 'image/jpeg'; 
     break; 
    case 'gif': 
     $mimeType = 'image/gif'; 
     break; 
} 


$types = ($position == 1) ? array('image', 'small_image', 'thumbnail') : array(); 


$newImage = array(
    'file' => array(
     'content' => base64_encode($file_location), 
     'mime' => $mimeType, 
     'name' => pathinfo($sku."-".$position, PATHINFO_FILENAME), 
    ), 
    'label' => '', 
    'position' => $position, 
    'types' => $types, 
    'exclude' => 0, 
); 

$media = Mage::getModel('catalog/product_attribute_media_api'); 
$media->create($sku, $newImage); 
//end save new image 

我的問題是,當我刪除圖像WS-ACCESS-000036-黑2.JPG從磁盤和產品目錄,然後我添加新的WS-ACCESS-000036-黑2.JPG到它的產品庫加載了舊的WS-Access-000036-Black-2.jpg。
我在想它的緩存問題,但我已經清除了我的緩存,並且舊圖像不斷加載。
當我此行

'name' => pathinfo($sku."-".$position, PATHINFO_FILENAME), 

下更改名稱,這只是一切工作正常。
我需要保留原始文件名。
這是怎麼發生的?

回答

0

據瞭解,你仍然看到舊圖像,但你檢查新圖像是否插入磁盤的第二個位置?

如果插入的新圖片可能需要去管理,系統 - >緩存管理&刷新所有緩存+請刷新目錄圖片緩存。

也請嘗試在其他瀏覽器中檢查這一點。

謝謝。

+0

我以前試過這個,認爲這是一個緩存問題,但它沒有奏效。 – altoids

+0

您使用CDN嗎?如果是,那麼你需要刷新CDN。 –

0

做的一個 如果新的圖像插入那麼可能是你需要去管理,系統 - >緩存管理&刷新所有緩存+請刷新目錄圖像緩存

緩存清除後,將工作

+0

我以前曾嘗試過這是一個緩存問題,但它不起作用 – altoids

+0

是否可以共享您的演示管理鏈接或創建一個只訪問此功能的用戶 –

相關問題