Skip to content

Instantly share code, notes, and snippets.

@dfelton
Last active May 26, 2016 19:30
Show Gist options
  • Save dfelton/0ce890635c287e72ae27c378550e467a to your computer and use it in GitHub Desktop.
Save dfelton/0ce890635c287e72ae27c378550e467a to your computer and use it in GitHub Desktop.
Finds simple products which belong to a grouped product, and have no base image. Then assigns the base image from the grouped product to that simple product.
<?php
/**
* Finds simple products which belong to a grouped product, and have no base image.
* Then assigns the base image from the grouped product to that simple product.
*
* @category FirstScribe
* @package FirstScribe_Shell
* @author Darren Felton
*/
require 'abstract.php';
class FirstScribe_Shell_SimpleOfGroupedApplyBaseImage extends Mage_Shell_Abstract
{
public function run()
{
/* @var $collection Mage_Catalog_Model_Resource_Product_Collection */
/* @var $simples Mage_Catalog_Model_Resource_Product_Collection */
/* @var $simple Mage_Catalog_Model_Product */
/* @var $grouped Mage_Catalog_Model_Product */
/* @var $type Mage_Catalog_Model_Product_Type_Grouped */
ini_set('memory_limit', '512M');
echo PHP_EOL;
echo 'Fetching products...',PHP_EOL;
$collection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToFilter('type_id', 'grouped')
->addAttributeToSelect('image');
foreach ($collection as $grouped) {
// If configurable this has no images, it won't help us anyway.
if (false == $grouped->getData('image') || 'no_selection' == $grouped->getData('image')) {
continue;
}
$type = Mage::getModel('catalog/product_type_grouped')->setProduct($grouped);
$simples = $type->getAssociatedProductCollection()->addAttributeToSelect('image');
foreach ($simples as $simple) {
if (false == $simple->getData('image') || 'no_selection' == $simple->getData('image')) {
$filename = Mage::getBaseDir('media').DS.'catalog'.DS.'product'.$grouped->getData('image');
if (file_exists($filename)) {
$simple->addImageToMediaGallery($filename, array('image','small_image','thumbnail'),false,false);
try {
$simple->save();
echo 'Image added to simple product, ID: ',$simple->getId(),PHP_EOL;
} catch (Exception $e) {
echo $e->getMessage(),PHP_EOL;
}
}
}
}
}
echo 'SCRIPT COMPLETE',PHP_EOL,PHP_EOL;
}
}
$shell = new FirstScribe_Shell_SimpleOfGroupedApplyBaseImage();
$shell->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment