Programmatically add Magento products to categories

后端 未结 7 1876
执念已碎
执念已碎 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条回答
  •  萌比男神i
    2020-12-24 14:53

    After looking into the Magento API: Magento adds products to categories in the following way:

    public function assignProduct($categoryId, $productId, $position = null, $identifierType = null)
    {
        $category = $this->_initCategory($categoryId);
        $positions = $category->getProductsPosition();
        $productId = $this->_getProductId($productId);
        $positions[$productId] = $position;
        $category->setPostedProducts($positions);
    
        try {
            $category->save();
        } catch (Mage_Core_Exception $e) {
            $this->_fault('data_invalid', $e->getMessage());
        }
    
        return true;
    }
    

    And getting all the asigned products:

    public function assignedProducts($categoryId, $store = null)
    {
        $category = $this->_initCategory($categoryId);
    
        $storeId = $this->_getStoreId($store);
        $collection = $category->setStoreId($storeId)->getProductCollection();
        ($storeId == 0)? $collection->addOrder('position', 'asc') : $collection->setOrder('position', 'asc');;
    
        $result = array();
    
        foreach ($collection as $product) {
            $result[] = array(
                'product_id' => $product->getId(),
                'type'       => $product->getTypeId(),
                'set'        => $product->getAttributeSetId(),
                'sku'        => $product->getSku(),
                'position'   => $product->getPosition()
            );
        }
    
        return $result;
    }
    

提交回复
热议问题