Assuming you know the product ids and the simple products have values for the configurable attribute:
$configurable_product = Mage::getModel('catalog/product')->load($id_of_configurable);
$configurable_product->getTypeInstance()
->saveProducts(
$configurable_product,
$array_of_simple_product_ids
);
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
Best Answer
First get the configurable product:
I know this is no the fastest way to do it and it uses
load
in loops but if you don't need to delete hundred of products or you don't need to call this constanlly you should be OK