本文介绍了以编程方式将 Magento 产品添加到类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Magento 1.4.0.1.我有超过 21000 种简单的产品,每一种都属于一个类别.我的网站中有数百个类别.一些产品属于多个类别.有什么方法可以让我以编程方式将产品添加到多个类别中?

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 multiple categories.Is there some way for me to programmatically add products into multiple categories?

推荐答案

在 PHP 代码中,您可以在导入它们时将它们放入类别.

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

假设您有一个名为 $product 的产品和一个名为 $category_id 的类别 ID

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();

如果产品已经有类别并且您想再添加一个类别,那么您可以像这样使用 getCategoryIds():

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();

或者,正如 Joshua Peck 在评论中提到的,您可以使用 category_api 模型从类别中添加或删除产品,而不会影响其当前的类别分配:

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());

这篇关于以编程方式将 Magento 产品添加到类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 06:29