Skip to content

Instantly share code, notes, and snippets.

@jreinke
Created October 19, 2015 12:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jreinke/5a0b53be321b03ed8a11 to your computer and use it in GitHub Desktop.
Save jreinke/5a0b53be321b03ed8a11 to your computer and use it in GitHub Desktop.
Magento: copy images from one product to another
<?php
/**
* Copy all images from $productSrc to $productDest
*
* @param Mage_Catalog_Model_Product $productSrc
* @param Mage_Catalog_Model_Product $productDest
*/
public function copyProductImages(Mage_Catalog_Model_Product $productSrc, Mage_Catalog_Model_Product $productDest)
{
$images = array();
$baseDir = Mage::getSingleton('catalog/product_media_config')->getBaseMediaPath();
foreach ($productDest->getMediaAttributes() as $imageAttribute) {
/** @var Mage_Catalog_Model_Resource_Eav_Attribute $imageAttribute */
$imageAttributeCode = $imageAttribute->getAttributeCode();
$file = $baseDir . $productSrc->getData($imageAttributeCode);
if (file_exists($file)) {
if (!isset($images[$file])) {
$images[$file] = array();
}
$images[$file][] = $imageAttributeCode;
}
}
foreach ($images as $file => $imageAttributeList) {
try {
$productDest->addImageToMediaGallery($file, $imageAttributeList, false, false);
} catch (Exception $e) {
Mage::logException($e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment