Magento - 按类别 ID 获取产品

Magento - get products by category ids

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

我该怎么做?也许有这样的扩展。

使用以下代码将 php 页面(类别-name.php)添加到 Magento 根目录。您需要做一些修改才能使其正常工作。

/** 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))