Set related products magento 1

This tutorial explains how to set related products magento 1 programmatically. This example it reads the data from the CSV which contains the products sku and related product sku’s

Please refer the tutorial that explains how to import product programmatically and other magento tutorials.The below code assign the related product as shown below.

assign_related_products_magento_1

  • Initialise database connection
  • Read CSV data
  • Assign related products magento 1

Initialise database connection

Create the relatedproducts.php inside the root and add the following code.

intialise_database_connection_magento_1

Read CSV data

read_related_products_data_magento_1

Assign related products magento 1

function addRelatedProducts( $imported_products ) {
    
    foreach($imported_products as $imported_product) {
    
        $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $imported_product[0]);
        
        if($product)
        {
            $sRelatedSkus = $imported_product[25];
            $sRelatedSku = explode(',', $sRelatedSkus);
            $aParams = array();
            $nRelatedCounter = 1;

            foreach( $sRelatedSku as $sku )
            {
                $aRelatedProduct = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
                
                if(is_object($aRelatedProduct)) {
                    
                $aParams[$aRelatedProduct->getId()] = array('position' => $nRelatedCounter);
                $nRelatedCounter++;
                
                }
                else {
                    
                    echo 'Sku not existing : '.$sku.PHP_EOL;
                    
                }
            }

            $product->setRelatedLinkData($aParams);
            if($product->save())
                echo ' Related products assigned for '. $imported_product[0].' ' . $product->getName().PHP_EOL;
                
        }

    }
    
}

Share this Tutorial