Magento: using getModel to get product and category
I have some code that returns an array of product details including a url_path. To create a link to this product I have to know 开发者_高级运维the category and subcategory of the product. Unfortunately out all the data this method returns neither the category or sub category are pulled out.
Here is the code I have that gets a product:
$product_id = array(231, 230,229,228);
foreach ($product_id as $id){
$productDetails = Mage::getModel('catalog/product')->load($id)->getData();
echo $productDetails['url_path'].'<br />';
}
Is it possible to get the category and subcategory for each product?
you are looking for
foreach ($product_id as $id){
$categoryIds = Mage::getModel('catalog/product')->load($id)->getCategoryIds();
}
which will return you an array of category ids that the product belongs to.
Better way not to miss something with rewrites is to use core functionality. Mage_Catalog module has own url model, with which product urls can be modified.
So, the code will be:
$product_id = array(231, 230,229,228);
$urlModel = Mage::getSingleton('catalog/url');
foreach ($product_id as $id) {
$urlModel->refreshProductRewrite($id);
}
And it is no need to retrieve category ids for this purpose.
精彩评论