以下代碼允許您導入圖像並設置位置。它會根據數組中的圖像順序來設置位置,所以如果這不是必需的,但是希望這至少能夠讓您瞭解如何完成該操作,您需要更改該位置。
$sku = $product->getSku();
$media = Mage::getModel('catalog/product_attribute_media_api');
$position = 1;
foreach($mediaArray as $fileName) {
if (file_exists($fileName)) { // assuming $fileName is full path not just the file name
$pathInfo = pathinfo($fileName);
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($fileName),
'mime' => $mimeType,
'name' => basename($fileName),
),
'label' => 'whatever', // change this.
'position' => $position,
'types' => $types,
'exclude' => 0,
);
$media->create($sku, $newImage);
// OR (if you would rather use the product entity ID):
// $media->create($productId, $newImage, null, 'id');
$position++;
} else {
// image not found
}
}
好吧,有一個位置字段。我認爲可能有一個參數在每個產品的基礎上說「默認圖像」。這應該很好,謝謝。 – Nathan 2013-04-07 18:58:51
我在$ media-> create()語句中遇到了一個「not_created」錯誤。另外,有沒有辦法更改管理界面中的默認圖像?有時訂單不是我想要的,所以我只想通過用戶界面進行更改。 – Nathan 2013-04-07 19:59:57
在這種情況下,我會嘗試將一些調試代碼放入Mage_Catalog_Model_Product_Attribute_Media_Api類。如果您還不知道,可以在app/code/core/Mage/Catalog/Model/Product/Attribute/Media/Api.php中找到它。你應該能夠縮小故障發生的方式。請記住恢復之後對核心代碼所做的任何更改。是的,這可以在產品的圖像部分(目錄 - >管理產品)中手動更改。 – redjam13 2013-04-07 22:29:08