Assign related products magento 1

This tutorial explains how to assign related products magento 1 programmatically. The CSV file contain the products sku and related product sku’s

Please also refer 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

Leave a Reply

Your email address will not be published. Required fields are marked *

*