Apply two conditionals to a singel attribute in a Magento collection

I am currently trying to get products that are of a certain price range in Magento. I tried the first two logical ways I could think. The first one being to add two addAttributeToFilter() statements to my code.

$products->addAttributeToFilter('price', array('gteq' => $r['price_low']));
$products->addAttributeToFilter('price', array('lteq' => $r['price_high']));

No dice. This just gave me the second one.

Then what I decided to try was adding both conditionals to a single addAttributeToFilter() like this:

$price_array['gteq'] = $r['price_low'];
$price_array['lteq'] = $r['price_high'];
$products->addAttributeToFilter('price', $price_array);

Again just the high end. I did a getSelect() on my collection and confirmed it in the query that it is only applying the high end.

Does anyone know how I can get products that have a price range.

2 thoughts on “Apply two conditionals to a singel attribute in a Magento collection”

  1. Here is what I ended up having to do to make this work (Thanks Alan Storm! — Found on his guide on Magento’s website).

    if($has_low_price && $has_high_price) {
        $products->addFieldToFilter('price', array('gteq' => $r['price_low']));
        $products->addFieldToFilter('price', array('lteq' => $r['price_high']));
    } elseif($has_high_price) {
        $products->addAttributeToFilter('price', array('lteq' => $r['price_high']));
    } elseif($has_low_price) {
        $products->addAttributeToFilter('price', array('gteq' => $r['price_low']));
    } else {

    If you want to do ANDs you have to use addFieldToFilter not addAttributeToFilter.

  2. You’re almost there. I believe the syntax you are looking for is this:

    $filter = array(
        array("gteq" => $r['price_low']),
        array("lteq" => $r['price_high']),
    $products->addAttributeToFilter("price", $filter);

    It’s not very intuitive, but it works.

    Hope that helps!


Leave a Reply

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