简体   繁体   中英

Magento custom filter on listing page gives incorrect product count

I am displaying listing page with products. And I applied custom filter to filter out the products.

Code in list.phtml :

$postCodeQueryStr = $this->getRequest()->getParam('post_code');

$_productCollection = $this->getLoadedProductCollection()
        ->addAttributeToFilter(
                array(
                    array('attribute'=>'town', 'like' => ''.$postCodeQueryStr.'%'),
                    array('attribute'=>'post_code', 'like' => ''.$postCodeQueryStr.'%')
                )
        )

        ->clear()->addAttributeToSort('created_at', 'DESC');

To show count or products I used:

echo $_productCollection->getSize()

Here initially through $this->getLoadedProductCollection() , I get All products and then I am filter it using addAttributeToFilter() . It shows limited products actually. By this I mean it filters out to show limited products related to criteria.

在此处输入图片说明

But instead of showing filtered count, it shows whole count of products, it doesn't show count after filtering by criteria.

I am getting limited products in list, but count of them is old (before filter).

The problem is you are filtering on the template level , and the count is rendered in the toolbar before that. so you have to put your filter in the

function getLoadedProductCollection() 

which further uses the function

public function getProductCollection()
{
    $collection = Mage::getResourceModel('catalog/product_collection')
        ->setStoreId($this->getStoreId())
        ->addCategoryFilter($this);
    return $collection;
}

located at app/code/core/Mage/Catalog/Model/Category.php

you can add your filter here .

i will suggest you to not to edit this core file and switch it to your local folder .

let me know if there is any doubt.

thanks hope it will do your work.

you can modify the function like below according to your needs Just replace this function as below and you will all done. thanks

    public function getProductCollection()
    {
        $postCodeQueryStr = $_POST['post_code'];
        $collection = Mage::getResourceModel('catalog/product_collection')
            ->setStoreId($this->getStoreId())
            ->addCategoryFilter($this);
        if($postCodeQueryStr!=''){
$collection->addAttributeToFilter(
                array(
                    array('attribute'=>'town', 'like' => ''.$postCodeQueryStr.'%'),
                    array('attribute'=>'post_code', 'like' => ''.$postCodeQueryStr.'%')
                )
        )
        ->clear()->addAttributeToSort('created_at', 'DESC');
            }
        return $collection;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM