Wednesday, October 16, 2013

Displaying New Products in Magento with Pagination

Just recently we ran into an issue where we wanted to display all new products added to a specific category in our Magento site, with pagination. To make things more complicated, we wanted to display this by using a CMS page. The default functionality that Magento provides for new products just didn’t cut it in our case. We had to come up with something different and I am documenting it here for everyone’s benefit. This method will allow you to add new products to a Magento CMS page and pull up new products for any category you choose, or for the entire site. Whether you want to add new products to your CMS page by category or for the entire site, it’s up to you.

Adding New Products with Built in Magento Tools

First, let’s set the record straight. It is possible to display a list of new products in Magento using a default block. You can do this without any coding changes or modifications to Magento itself. This code will allow you to bring up a list of new products on one of your CMS pages. It is also possible to use this to bring new products up within a template file or on your homepage, though we are not covering that here.

{{block type="catalog/product_new" column_count="6" products_count="400" name="home.catalog.product.new" alias="product_homepage" template="catalog/product/new.phtml"}}

The above code will bring up your 400 newest products in 6 columns. You can change the column_count and products_count variable so that any number of columns or products is shown. You can display all of your newest products by changing the products_count variable to zero. OK, so this is all good, but it’s not what we want. We want to display an entire page of our new products with the pagination toolbar, and we want to display the products with a Magento CMS page. It’s quite simple to accomplish this, and here is how you can do it.

Display New Products in Magento with Pagination

The following steps will help you to add new products to a Magento CMS page and show pagination for the products.
  1. Create all of the folders in the following path if they do not already exist.
    app/code/local/Mage/Catalog/Block/Product
    Note: We do not want to modify core Magento code so we create our own path in the “local” folder
  2. Create a New.php file and place it in the following location:
    app/code/local/Mage/Catalog/Block/Product/New.php
    Note: We named our file New.php which worked for our purposes.
    Note: If your file is named “New.php” it will overwrite Magento’s default New.php page located in app/code/core/Mage/Catalog/Block/Product. If you are going to be using the default New.php file included with Magento in other parts of your site you may want to name your file differently.
  3. Add the following code to your New.php file (The key to the pagination is extending the List class):
    //Code
    <?php

    class Mage_Catalog_Block_Product_New extends Mage_Catalog_Block_Product_List
    {
       function get_prod_count()
       {
          //unset any saved limits
          Mage::getSingleton('catalog/session')->unsLimitPage();
          return (isset($_REQUEST['limit'])) ? intval($_REQUEST['limit']) : 12;
       }// get_prod_count

       function get_cur_page()
       {
          return (isset($_REQUEST['p'])) ? intval($_REQUEST['p']) : 1;
       }// get_cur_page

       /**
        * Retrieve loaded category collection
        *
        * @return Mage_Eav_Model_Entity_Collection_Abstract
       **/
       protected function _getProductCollection()
       {
          $todayDate  = Mage::app()->getLocale()->date()->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);

          $collection = Mage::getResourceModel('catalog/product_collection');
          $collection->
    setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds());

          $collection = $this->_addProductAttributesAndPrices($collection)
             ->addStoreFilter()
             ->addAttributeToFilter('news_from_date', array('date' => true, 'to' => $todayDate))
             ->addAttributeToFilter('news_to_date', array('or'=> array(
                0 => array('date' => true, 'from' => $todayDate),
                1 => array('is' => new Zend_Db_Expr('null')))
             ), 'left')
             ->addAttributeToSort('news_from_date', 'desc')
             ->setPageSize($this->get_prod_count())
             ->setCurPage($this->get_cur_page());

          $this->setProductCollection($collection);

          return $collection;
       }// _getProductCollection
    }// Mage_Catalog_Block_Product_New
    ?>
  4. Alright – save your New.php file. Now it’s time to add your Magento CMS page and get it to show the new products.
Now, I’m assuming you already know how to add a CMS page to your Magento site so we will not be covering it in this post. Once you have added your CMS page, there are a couple of ways to get your new products to show up. I plan on going through both of them below.

Route 1 – Add New Products to a Magento Page with the Magento Block

Remember that good old block code we used to get our products to show up at first? Well we can use that again, however this time we will modify it to take advantage of the list.phtml template file. Take the following block and put it in the Content area of your CMS page.
{{block type="catalog/product_new" column_count="6" products_count="0" name="home.catalog.product.new" alias="product_homepage" template="catalog/product/list.phtml"}}
You’ll notice that the only real difference between the code shown at the beginning of this post and the code shown above is the usage of the list.phtml template file. This file gives us access to the Magento toolbar and pager options. Some of you may have noticed a slight issue with this approach. We are displaying 6 columns of products, but the number of products per page is set to 10. Also – you may see that you actually have 15 products for sale but only one page of 12 products shows. This leads us to the second option of displaying new products with Magento.

Route 2 – Add New Products to a Magento page using Layout XML

Adding new products to a Magento page using Layout XML gives us a bit more control over what is displayed on our CMS page. In order to add Layout XML you will need to open the Design tab of your CMS page. You’ll notice a textarea entitled Layout Update XML. This box is where we can put our XML to display new products. Copy and paste the following XML into your Layout Update XML box.
<reference name="content">
   <block type="catalog/product_new" name="product_new" template="catalog/product/list.phtml">
      <action method="setCategoryId"><category_id>10</category_id></action>
      <action method="setColumnCount"><column_count>6</column_count></action>
      <action method="setProductsCount"><count>0</count></action>
      <block type="catalog/product_list_toolbar" name="product_list_toolbar" template="catalog/product/list/toolbar.phtml">
         <block type="page/html_pager" name="product_list_toolbar_pager" />
         <action method="setDefaultGridPerPage"><limit>12</limit></action>
         <action method="addPagerLimit"><mode>grid</mode><limit>12</limit></action>
         <action method="addPagerLimit"><mode>grid</mode><limit>24</limit></action>
         <action method="addPagerLimit"><mode>grid</mode><limit>36</limit></action>
         <action method="addPagerLimit"><mode>grid</mode><limit>48</limit></action>
         <action method="addPagerLimit" translate="label"><mode>grid</mode><limit>all</limit><label>All</label></action>
      </block>
      <action method="addColumnCountLayoutDepend"><layout>one_column</layout><count>6</count></action>
      <action method="setToolbarBlockName"><name>product_list_toolbar</name></action>
   </block>
</reference>
Let’s quickly go over what this does.
  1. <block type="catalog/product_new" name="product_new" template="catalog/product/list.phtml">
    First we set the block type and the template we are using. In our case we set the block type to “catalog/product_new” which pulls the block from the New.php file we placed in our local directory at the beginning of the post.
  2. The template we are using is “list.phtml” which gives us access to the Pager and Toolbar.
  3. <action method="setCategoryId"><category_id>10</category_id></action>
    setCategoryId – Next we set the Category ID. In our situation we had two Magento stores running off of two different root categories. We changed the category ID depending on which category we wanted to pull new products for. You can set this to whatever category you want, or remove the line altogether.
    Note: You can put this XML on multiple pages. So you could have a page for new Children clothing and a page for new Adult clothing. You would simply need to put the same XML on each page and change the Category ID to reflect the children and adult clothing categories.
  4. <action method="setColumnCount"><column_count>6</column_count></action>
    setColumnCount – This allows us to show six products in one row on the page. We set the column count to six because this fit our design. Feel free to set it to whatever suits your purposes.
  5. <action method="setProductsCount"><count>0</count></action>
    setProductsCount – Setting the products count. Leave this set to zero in order to display all new products – change it if you only wish to limit display to a certain number.
  6. <block type="catalog/product_list_toolbar" name="product_list_toolbar" template="catalog/product/list/toolbar.phtml">
             <block type="page/html_pager" name="product_list_toolbar_pager" />
    Adds the toolbar and pager.
  7. <action method="setDefaultGridPerPage"><limit>12</limit></action>
    setDefaultGridPerPage – Configure the toolbar to show what the number of products you wish. By default we are showing 12 products per page, which is two rows of six columns.
  8. <action method="addPagerLimit"><mode>grid</mode><limit>12</limit></action>
    addPagerLimit – These all add options to the toolbar which will allow your customers to choose how many products they want to see on one page. The XML given will allow the customer to choose to display 12, 24, 36, 48, or All products on one page.
  9. <action method="addColumnCountLayoutDepend"><layout>one_column</layout><count>6</count></action>
    Finally, in our design, the one_column layout has to be selected in order for 6 columns to show up (otherwise there isn’t enough room).
  10. <action method="setToolbarBlockName"><name>product_list_toolbar</name></action>
    Set the toolbar name.
  11. You may notice one caveat with this approach. You need to make sure there is content in the Content area of the CMS page. Any easy way around this is to enter a “<br />” in the html portion of the Content entry section.
  12. Save your page!

No comments:

Post a Comment