Magento 1.9如何展示近7日畅销商品?
Solution for Showing Last 7 Days' Bestsellers in Magento 1.9 Product Slider
Hey there! Let's fix your bestsellers widget to only pull data from the last 7 days instead of all-time. Your current code uses the reports/product_collection which defaults to lifetime order quantities—we just need to add a date range filter to narrow it down.
Step-by-Step Modifications
The key change is passing a date range to the addOrderedQty() method. Magento's reports/product_collection accepts start and end date parameters for this method, so we'll calculate the 7-day window and inject it into the collection.
Here's the updated version of your block class with the necessary changes:
<?php class Bigdrop_ProductSlider_Block_Bestsellers extends Bigdrop_ProductSlider_Block_Slider_Abstract { protected $_code = 'bestsellers'; /** * Retrieves sort by param * * @return string */ protected function _getSortByParam() { return 'ordered_qty'; } /** * Preparing product collection of the current Slider * * @return Mage_Catalog_Model_Resource_Product_Collection|Mage_Reports_Model_Resource_Product_Collection */ protected function _prepareSliderCollection() { // Calculate the start date: 7 days ago from today (store time zone compliant) $startDate = Mage::getModel('core/date')->date('Y-m-d H:i:s', strtotime('-7 days')); $endDate = Mage::getModel('core/date')->date('Y-m-d H:i:s'); $collection = Mage::getResourceModel('reports/product_collection') ->addOrderedQty($startDate, $endDate); // Add date range filter here if (Mage::helper('catalog/product_flat')->isEnabled()) { $collection->getSelect() ->joinInner(array( 'e2' => 'catalog_product_flat_' . Mage::app()->getStore()->getId() ), 'e2.entity_id = e.entity_id'); } else { $this->assignAttributes($collection); } $this->_applyStockVisibilityFilter($collection); $this->_setOrderToCollection($collection); $collection->getSelect()->limit($this->_getLimit()); return $collection; } }
Key Changes Explained
- Date Range Calculation: We use
Mage::getModel('core/date')to ensure we're using the store's time zone (critical for accurate date filtering across different regions). - Updated
addOrderedQty(): The method now takes$startDateand$endDatearguments, which tells Magento to only count orders placed within the last 7 days. - Preserved Existing Logic: All your original code for flat product joins, stock/visibility filters, sorting, and result limits stays intact—we're just narrowing the data set to your desired time frame.
Quick Post-Update Checks
After updating the code, make sure to:
- Clear Magento's frontend and backend cache to apply the changes
- Test by placing a test order for a product and confirming it appears in the slider within the 7-day window
- Verify that out-of-stock or invisible products still get filtered out as expected
内容的提问来源于stack exchange,提问作者Artur Rain
相关产品推荐
相关产品推荐

