浏览文章

文章信息

Magento2 获取分类属性筛选接口|get category attribute filters by rest api 13754

1、分类属性筛选接口

  /**
     * DESC:获取分类属性筛选
     *
     * @Author   秋枫雁飞
     * @Email:   aiweline@qq.com
     * @WebSite: www.aiweline.com
     * @Forum:   https://bbs.aiweline.com
     *
     * 参数:
     * @param int $categoryId
     * @return mixed
     */
    public function getFilter($categoryId)
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $filterableAttributes = $objectManager->getInstance()->get(\Magento\Catalog\Model\Layer\Category\FilterableAttributeList::class);
        $appState = $objectManager->getInstance()->get(\Magento\Framework\App\State::class);
        $layerResolver = $objectManager->getInstance()->get(\Magento\Catalog\Model\Layer\Resolver::class);
        $filterList = $objectManager->getInstance()->create(
            \Magento\Catalog\Model\Layer\FilterList::class,
            [
                'filterableAttributes' => $filterableAttributes
            ]
        );
        $layer = $layerResolver->get();
        if($categoryId != 0)
        {
            $layer->setCurrentCategory($categoryId);
        }
        $filters = $filterList->getFilters($layer);
        $maxPrice = $layer->getProductCollection()->getMaxPrice();
        $minPrice = $layer->getProductCollection()->getMinPrice();
        $i = 0;
        $finalFilters = [];
        $uid = 0;
        foreach ($filters as $filter) {
            $uid++;
            $finalFilters[$i]['field'] = $filter->getRequestVar();
            $label = ($filter->getRequestVar() == 'cat') ? 'Category' : $filter->getRequestVar();
            $finalFilters[$i]['id'] = $uid;
            $finalFilters[$i]['label'] = ucfirst($label);
            if($filter->getRequestVar() == "price") {
                $finalFilters[$i]['min-price'] = $minPrice;
                $finalFilters[$i]['max-price'] = $maxPrice;
            }
            $k = 0;
            foreach ($filter->getItems() as $item) {
                $k++;
                $optionLabel = strip_tags($item->getLabel());
                $optionValue = $item->getValue();
                $count = $item->getCount();
                $finalFilters[$i]['value'][] = array('label' => $optionLabel, 'value' => $optionValue,'count' => $count);
            }
            $i++;
        }
        $fil = [];
        foreach ($finalFilters as $fill) {
            if (isset($fill['value']))
                $fil[] = $fill;
        }
        return $fil;
    }


原创