Question

Can somebody explain why setCategoryIds($ids) changes the product's visibility to Catalog,Search from whatever else it was (in my encounter, I was working with Search-view products)?

Here's the code that makes all of the products in $categoryId to have visibility Catalog,Search after the save() when they originally had Search. I restored all of my products and tested it to verify as well.

$productCollection = Mage::getModel('catalog/category')->load($categoryId)
    ->getProductCollection() 
    ->addAttributeToSelect(array('name','price','special_price','sku','small_image'));

foreach($productCollection as $product) {
    $catIds = $product->getCategoryIds();
    $product->setCategoryIds($catIds);
    $product->save();
}
Was it helpful?

Solution

The reason is that you're saving the product but you've not loaded the visibility as part of the product collection. Catalog, Search is the default visibility.

Try this:

$productCollection = Mage::getModel('catalog/category')->load($categoryId)
    ->getProductCollection() 
    ->addAttributeToSelect(array('name','price','special_price','sku','small_image'))
    ->joinAttribute('visibility', 'catalog_product/visibility', 'entity_id', null, 'inner');

Now when you save the product it should retain its original visibility setting.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top