Ho to get product by attribute or category in magento

Getting products by attribute or category in Magento

Like all other items in Magento store products have its own model and collection that can be used for getting list of products. So basic thing we do is getting instance of products collection:

At the same time we can specify which product attributes we want to get. For this we can use addAttributeToSelect method. You can specify them separately in each method or pass array as argument.

Or in case you need to get all of the product attributes you can use:

Now we can filter collection by some attribute, this can be done with addAttributeToFilter method. It can be simple one attribute filter:

Or they can be stacked several to each other.

Adding multiple filter will use AND logic, so both conditions need to match for product to be returned by collection. This function also supports different conditional statements that are similar to the once you’ve seen in SQL queries. Here is some examples:

Getting products by category can be done in some different way – first we get category item by id for example, and then getting collection of products for this category.

Or we can join category table for more complex situation, following example gets all products from categories with specified ids:

Finally you can iterate your collection of products:



Leave a Reply

Your email address will not be published. Required fields are marked *