以编程方式将Magento产品添加到类别 [英] Programmatically add Magento products to categories

查看:51
本文介绍了以编程方式将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产品添加到类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆