문제

In Magento2 - I've created a yes/no toggle category attribute named is_featured, its shown as "Homepage Category" in the screenshot below.

enter image description here

I'd like to be able to display (on the homepage cms page) all categories with this category attribute set to yes, I'd need to grab the category title, url, thumbnail etc, does anyone have any recommended steps on how to achieve this?

도움이 되었습니까?

해결책

Hi Below is the standard way to achieve it.

    namespace NameSpace\Module\Block;


    class FeaturedCategories extends \Magento\Framework\View\Element\Template
{


     protected $categoryCollectionFactory;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
        array $data = []
    ) {
        $this->categoryCollectionFactory = $categoryCollectionFactory;
        parent::__construct($context, $data);
    }

    public function getFeaturedCategories()
    {
        $collection = $this->categoryCollectionFactory->create();
        $collection->addAttributeToSelect('*')
            ->addAttributeToFilter('is_featured_category', '1')
            ->addAttributeToFilter('is_active', '1')
            ->setPageSize(10)
            ->setCurPage(1);

        return $collection;
    }
}

다른 팁

Please try with below code to filter with is_featured is yes

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();    
$category = $objectManager->create('Magento\Catalog\Model\ResourceModel\Category\Collection');
        $category->addAttributeToSelect('*')
        ->setPageSize(1)
        ->addAttributeToFilter('is_featured',['eq'=>1])
        ->setOrder('updated_at', 'desc');

try its work for me

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 magento.stackexchange
scroll top