
MAGENTO 1.X – ASSIGN RELATED PRODUCTS PROGRAMMATICALLY
The following standalone script will help you to assign related products according to some filters.
We assumed that you know how to work with Magento standalone shell scripts, if you are not the case, please see first the following article: Magento 1.x – How to create a standalone script .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
<?php require_once(dirname(__FILE__).'/../app/Mage.php'); require_once 'abstract.php'; class Offset101_Shell_FillRelatedProducts extends Mage_Shell_Abstract { public function run() { $products = Mage::getModel('catalog/product')->getCollection() ->addAttributeToSelect("id") ->addAttributeToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED)) ->addAttributeToFilter('sku', array('eq' => '6-9069-13-SN')) ->load(); // Iterate through all products where i want to assign related products. foreach ($products as $_product) { $_product->load(); if(!empty($_product->getRelatedProductIds())){ var_dump($_product->getSku() . " - HAS RELATED PRODUCTS"); continue; } var_dump($_product->getData('sku')); // Get related products according to some filters // (in this case, we are adding related products with same value on 'theme' property) $relatedProducts = Mage::getModel('catalog/product')->getCollection() ->addAttributeToSelect(array("id","theme")) ->addFieldToFilter('theme', $_product->getData('theme')) ->addFieldToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED)) ->setPageSize(20) ->load(); $insertIt = array(); // We will create an array with all related products. foreach ($relatedProducts as $relatedProduct) { if($relatedProduct->getId() == $_product->getId()) continue; $relatedProduct->load(); $insertIt[$relatedProduct->getId()] = array('position' => 0, 'qty' => ''); } var_dump(count($insertIt)); try { $_product->setRelatedLinkData($insertIt)->save(); echo "DONE"; } catch (Exception $e) { echo "There is problem with products, please refresh the page to see the result"; } } } } Mage::init(); $shell = new Offset101_Shell_FillRelatedProducts(); $shell->run(); |