Magento-1.9 Configurable Product – Duplicate Configurable Products Programmatically

configurable-productduplicatemagento-1.9

I want to duplicate configurable Products with their associated products programmatically in Magento. Can anyone help regarding this.

Best Answer

You can try this code.

$productId = 2;

//Load configurable product
$product = Mage::getModel('catalog/product')->load($productId);

//Getting children ids
$childs = Mage::getResourceSingleton('catalog/product_type_configurable')
            ->getChildrenIds($productId);

$newChildIds = array();
foreach ($childs as $childId) {
    //duplicate child products
    $newChildProduct = Mage::getModel('catalog/product')->load($childId)->duplicate();
    $newChildIds[] = $newChildProduct->getId();
}

//Duplicate configurable product
$newProduct = $product->duplicate();

//Attach simple products to new configurable
Mage::getResourceSingleton('catalog/product_type_configurable')
    ->saveProducts($newProduct, $newChildIds);

But after duplication of product, new product will be disabled and without SKU. You can enable it and generate SKU for new product added this code:

$newProduct->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
    ->setSku('new_sku');

$newProduct->getResource()->save($newProduct);

EDIT

Try this code for copying attributes (it save attributes):

//Get product attributes
$usedProductAttributeIds = $product->getTypeInstance()->getUsedProductAttributeIds();
$configurableAttributesData = $product->getTypeInstance()->getConfigurableAttributesAsArray();

//Remove some items from attributes
foreach ($configurableAttributesData as $key => $data) {
    unset($configurableAttributesData[$key]['id'], $configurableAttributesData[$key]['values'][0]['value_index']);
}

And after all operations with new product add this code:

$newProductId = $newProduct->getId();

//I dont know, but product must be reloaded.
$newProduct = Mage::getModel('catalog/product')->load($newProductId);    

//Set all attributes
$newProduct->getTypeInstance()->setUsedProductAttributeIds($usedProductAttributeIds);
$newProduct->setConfigurableAttributesData($configurableAttributesData);
$newProduct->setCanSaveConfigurableAttributes(true);

$newProduct->save();

Hope this helps