2

Is there a way to get all products by a specific attribute value? For example: how can I get all the products where the attribute color is red?

1 Answer 1

5

You can use below code

class GetProducts{
  protected $_productRepository;

  protected $_searchCriteriaBuilder;

  public function __construct(
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
    \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
   ) {
     $this->_productRepository = $productRepository;
     $this->_searchCriteriaBuilder = $searchCriteriaBuilder;
   }

public function getProductCollection(){
  $searchCriteria = $this->_searchCriteriaBuilder->addFilter('color', 4, 'eq')->create(); // 4 is the option id, may be red/green/blue, check in admin
  $searchResults = $this->_productRepository->getList($searchCriteria);
  $productsIds = $searchResults->getItems();
  return $productsIds;
}

Hope this may help you

2
  • Works like a charm, thanks!
    – Stijn DR
    Commented Mar 3, 2020 at 15:21
  • @StijnDR, Thanks for accepting!! Commented Mar 3, 2020 at 15:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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