Recently, I needed to associate a large number of products with a specific “store” in Magento. Rather than go through each product individually, I thought it might be quicker to update them programmatically via a script.
To simplify the script for an example, I’m going to grab all of the products, and here, I’m going to set them to simply the default website we’ve got set up.
The setWebsiteIds()
function takes an array of integers for its input, so you can associate a product with multiple websites at once if needs-be.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
/********************************************** // associate products with website // tested with > Magento 1.7 **********************************************/ require_once '../app/Mage.php'; Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); umask(0); $productCollection = Mage::getModel('catalog/product') ->getCollection() ->addAttributeToSelect('*'); foreach ($productCollection as $product) { $product->setWebsiteIds(array(1)); $product->save(); } |
If you need to retreive a list of your website ids or store ids from the database via script, Mage::App has the function you’re looking for:
1 2 3 4 5 6 7 8 |
foreach (Mage::app()->getWebsites() as $website) { foreach ($website->getGroups() as $group) { $stores = $group->getStores(); foreach ($stores as $store) { // logic here } } } |
Image Credit: Jims_photos
Comment or tweet @douglasradburn