Filter products without images on Magento frontend

2019-08-04 07:29发布

问题:

I am trying to filter products without images on Magento frontend but with half success.

I added the following code:

//$_productCollection=$this->getLoadedProductCollection();
$_productCollection = clone $this->getLoadedProductCollection();
$_productCollection->clear()
    ->addAttributeToFilter('image', array('neq' => 'no_selection'))
    ->load();

to:

app/design/frontend/default/[my_theme]/template/catalog/product/list.phtml

The products get filtered nicely but the page number and item count doesn't get updated.

I followed this link:

Magento - list.phtml filtering product collection not giving correct pagination

It seems to make sense, the product isn't getting filtered at a global scale so some parts of the website isn't properly updating.

I am not sure how to implement his solution as I am a newbie in Magento, seems like it worked for the person but maybe my case is different.

Please help.

回答1:

Figured it out myself! Hopefully someone could benefit from this!

Overwrite _beforeToHtml() in app/code/core/Mage/Catalog/Block/Product/list.php [BACKUP FILE]

protected function _beforeToHtml()
{
    $toolbar = $this->getToolbarBlock();

    // called prepare sortable parameters
    $collection = $this->_getProductCollection();

    // use sortable parameters
    if ($orders = $this->getAvailableOrders()) {
        $toolbar->setAvailableOrders($orders);
    }
    if ($sort = $this->getSortBy()) {
        $toolbar->setDefaultOrder($sort);
    }
    if ($dir = $this->getDefaultDirection()) {
        $toolbar->setDefaultDirection($dir);
    }
    if ($modes = $this->getModes()) {
        $toolbar->setModes($modes);
    }

    // insert start       
    $collection->addAttributeToFilter('image', array('neq' => 'no_selection'));
    // insert end   

    // set collection to toolbar and apply sort
    $toolbar->setCollection($collection);

    $this->setChild('toolbar', $toolbar);
    Mage::dispatchEvent('catalog_block_product_list_collection', array(
        'collection' => $this->_getProductCollection()
    ));

    $this->_getProductCollection()->load();

    return parent::_beforeToHtml();
}

Sources: http://www.magentocommerce.com/boards/viewthread/73507/