I have created one custom attribute and also i have added some product under that attribute now i need product collection of that attribute. Below is my block code for collection but it's not working

public function getCustomProduct()
        $collection =  $this->_productCollectionFactory->create()
                        ->addAttributeToFilter('status', '1')
                        ->addAttributeToFilter('featured_product', '1')
                        ->addFieldToFilter('visibility', $this->_productVisibility->getVisibleInSiteIds());

    return $collection;

i need all products in template file those have under featured_product attribute. Please help me. Thanks in Advanced

namespace Vendor\Module\Block;

class Featured extends \Magento\Framework\View\Element\Template
    public function __construct(
        \Magento\Catalog\Block\Product\Context $context, 
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        \Magento\Catalog\Model\Product\Visibility $catalogProductVisibility,
        array $data = []
    ) {
        $this->_productCollectionFactory = $productCollectionFactory;        
        $this->catalogProductVisibility = $catalogProductVisibility;

    public function getProducts()
        $collection = $this->_productCollectionFactory->create();
        $collection = $this->_productCollectionFactory->create()->addAttributeToSelect('*')->addAttributeToFilter('status', '1')
                        ->addAttributeToFilter('featured_product', '1');

        return $collection;


You can use above code to get featured product.

  • After using your code in block file, again i'm getting blank page at frontend. And my template code is $collection = $block->getProducts(); var_dump($collection); – Pinku Dec 28 '16 at 13:09
  • $collection = $block->getProducts(); $totalProducts = count($collection); <?php if($totalProducts > 0){ foreach($products as $product){ print_r($product->getData()); } ?> <?php } ?> – Rakesh Jesadiya Dec 28 '16 at 13:13
  • Still i am getting blank page after using your code. – Pinku Dec 29 '16 at 4:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.