Programmatically add Magento products to categories

后端 未结 7 1906
执念已碎
执念已碎 2020-12-24 14:31

I am using Magento 1.4.0.1. I have over 21000 simple products, each entered into a single category. There are hundreds of categories in my site. Some products belong in mult

7条回答
  •  抹茶落季
    2020-12-24 15:00

    In PHP code you can put them into the category while you are importing them.

    Say you have a product called $product and a category ID called $category_id

    You can set the categories which a product belongs to by doing the following

    $categories = array($category_id);
    $product->setCategoryIds($categories);
    $product->save();
    

    If the product already has categories and you'd like to add one more then you can use getCategoryIds() like this:

    $categories = $product->getCategoryIds();
    $categories[] = $categoryId;
    $product->setCategoryIds($categories);
    $product->save();
    

    Or, as mentioned by Joshua Peck in the comments, you can use the category_api model to add or remove a product from a category without affecting it's current category assignments:

    Mage::getSingleton('catalog/category_api')
      ->assignProduct($category->getId(),$p‌​roduct->getId());
    
    Mage::getSingleton('catalog/category_api')
      ->removeProduct($category->getId(),$p‌​roduct->getId());
    

提交回复
热议问题