Magento - 按类别ID获取产品

时间:2015-04-07 20:15:58

标签: magento categories product

我想使用网址http://mydomain.test/categoru-name.html?cat=9,10,40。我需要使用类别ID(9,10,40)从类别类别名称和子类别中获取所有产品。

我该怎么做?也许有这样的延伸。

1 个答案:

答案 0 :(得分:0)

使用以下代码向Magento root添加php页面(category-name.php)。您需要做一些修改才能使其发挥作用。

/** START Include Magento **/
define('MAGENTO_ROOT', getcwd());

$compilerConfig = MAGENTO_ROOT . '/includes/config.php';
if (file_exists($compilerConfig)) {
    include $compilerConfig;
}else{exit;}

$mageFilename = MAGENTO_ROOT . '/app/Mage.php';

if (file_exists($mageFilename)) {
    require_once $mageFilename;
}else{exit;}

Mage::app();
/** END Include Magento **/

// This is not a complete code. You need to fill in.

// Add from query paramter
$categoryIds = array("Insert IDs from URL");
$categoryIdList = array();
array_push($categoryIdList,$categoryIds); //Collect child category IDs

foreach($categoryIds as $Catid){
    $cat = Mage::getModel('catalog/category')->load($Catid);
    $subCats = $cat->getChildren();
    $arrSubCats = explode(',',$subCats);
    array_push($categoryIdList,$arrSubCats); //Collect child category IDs

    // Go another level down
        foreach($arrSubCats as $Catid){
        $cat = Mage::getModel('catalog/category')->load($Catid);
        $subSubCats = $cat->getChildren();
        $arrSubSubCats = explode(',',$subSubCats);
        array_push($categoryIdList,$arrSubSubCats); //Collect child category IDs

        // Go another level down
        // Another foreach loop for  $arrSubSubCats
    }
}

// Now we have all categoryIds in the tree.
// Get all products.
$collection = Mage::getModel('catalog/product')
                             ->getCollection()
                             ->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
                             ->addAttributeToSelect('*')
                             ->addAttributeToFilter('category_id', array('in' => $categoryIdList))