We had a task to create references on the previous and the next items in a category. Of course, there are several similar solutions, but all of them don't consider the fact that flat_tables can be turned on. This neglect leads to errors, which appear because of the application of impossible mechanism of access to the part of information on categories and products.
Ready code, which allows to get urls to the nearest goods, considers flat_tables:
Initializing:
app/etc/modules/Mygento_Prevnext.xml
<config>
<modules>
<Mygento_Prevnext>
<active>true</active>
<codePool>local</codePool>
</Mygento_Prevnext>
</modules>
</config>
app/etc/modules/Mygento_Prevnext.xml
Now Magento has the information about your new module. Create the module, which will be placed in directory
app/code/local/Mygento/Prevnext
The structure of module folders:
magento/app/code/local/
Mygento/
Prevnext/
Block/
etc/
Helper/
Model/
sql/
File of module configuration:
app/code/local/Mygento/Prevnext/etc/config.xml
<?xml version="1.0"?>
<config>
<modules>
<Mygento_Customer>
<version>1.0</version>
</Mygento_Customer>
</modules>
<global>
<helpers>
<prevnext>
<class>Mygento_Prevnext_Helper</class>
</prevnext>
</helpers>
</global>
</config>
Helper file:
app/code/local/Mage/Prevnext/Helper/Data.php
<?php
class Mygento_Prevnext_Helper_Data extends Mage_Core_Helper_Abstract {
public function getPrevNext() {
$_category = Mage::getSingleton('catalog/layer')->getCurrentCategory();
$_currentCategoryId = $_category->getId();
$_prodId = Mage::registry('current_product')->getId();
$_category->load($_currentCategoryId);
$_collection = $_category->getProductCollection()
->addAttributeToFilter('status', 1)
->addAttributeToFilter('visibility', 4);
$new = array();
//Foreach for category
foreach ($_collection as $_collectionItem) {
array_push($new, $_collectionItem->getId());
}
//Foreach for direct product url
if ($new == NULL) {
foreach (Mage::getModel('catalog/product')->getCollection() as $_collectionItem) {
array_push($new, $_collectionItem->getId());
}
}
$new = array_flip($new);
$keys = array_flip(array_keys($new));
$values = array_keys($new);
//Prev product id
if (($keys[$_prodId] - 1) < 0) {
$x = count($new) - 1;
} else {
$x = $keys[$_prodId] - 1;
}
//Next product id
if (($keys[$_prodId] + 1) > count($new) - 1) {
$y = 0;
} else {
$y = $keys[$_prodId] + 1;
}
unset($new);
// Get products Url
$_Prevurl = Mage::getModel('catalog/product')->load($values[$x])->getProductUrl();
$_Nexturl = Mage::getModel('catalog/product')->load($values[$y])->getProductUrl();
$data = array($_Prevurl, $_Nexturl);
return $data;
}
}
The module is ready, and now lets use it in view.phtml:
<?php $urls = Mage::helper('prevnext')->getPrevNext(); ?>
<a class="prev-product" href="<?php echo $urls[0]; ?>"></a>
<a class="next-product" href="<?php echo $urls[1]; ?>"></a>
If you want, you can download the ready module