Wednesday, June 9, 2010

Adding related products, up-sells and cross-sells programmaticly

Problem:
Adding related products, up-sells and cross-sells programmaticly.
http://www.magentocommerce.com/boards/viewthread/195440/

Possible solution:

In order to set related, up-sells and crosssells you need to do the following
Let's assume that the current product is $_product (that you got by doing Mage::getModel('catalog/product')->load(SOME ID))
//for related
$_product->setRelatedLinkData($param);
//for up-sells
$_product->setUpSellLinkData($param);
//for crosssells
$_product->setCrossSellLinkData($param);
$param is an array with the following structure
$param = array(
$associatedProductId=>array(
'position'=>$associatedProductPosition
)
)

Here is an example. Let's say you want to add products with ids 101 and 102 as related products to $_product on positions 3 and 5.
You should do something like this:

$param = array(
101=>array(
'position'=>3
),
102=>array(
'position'=>5
)
);
$_product->setRelatedLinkData($param);
//here ... some other product operations and in the end
$_product->save();

It works the same for up-sells and crosssels.

2 comments:

  1. What is the position referring to?

    ReplyDelete
    Replies
    1. "position" represents the order in which the related products (and others) are displayed in the frontend.

      Delete