Learn how to modify K2 item navigation process to provide a previous and next for the first and last item in a category.
It is required to modify the item navigation logic so that:
If first category item render last item as previous link
If last category item display first item as next link
Here is how to implement it...
The K2 item navigation logic is implemented in two methods of the item model class K2ModelItem::getPreviousItem()
and K2ModelItem::getNextItem()
This file path is frontend/components/com_k2/models/item.php
So, to find the last item as the previous link in case the current item is the first category item, you will modify the getPreviousItem() method by adding this code snippet directly above the return $row;
line:
// Start of hack
if(is_null($row)){
// Get last item
if ($ordering == "0")
{
$query = "SELECT * FROM #__k2_items WHERE id > {$id} AND catid={$catid} AND published=1 AND ( publish_up = ".$db->Quote($nullDate)." OR publish_up <= ".$db->Quote($now)." ) AND ( publish_down = ".$db->Quote($nullDate)." OR publish_down >= ".$db->Quote($now)." ) {$accessCondition} AND trash=0 {$languageCondition} ORDER BY ordering DESC";
}
else
{
$query = "SELECT * FROM #__k2_items WHERE id != {$id} AND catid={$catid} AND ordering > {$ordering} AND published=1 AND ( publish_up = ".$db->Quote($nullDate)." OR publish_up <= ".$db->Quote($now)." ) AND ( publish_down = ".$db->Quote($nullDate)." OR publish_down >= ".$db->Quote($now)." ) {$accessCondition} AND trash=0 {$languageCondition} ORDER BY ordering DESC";
}
$db->setQuery($query, 0, 1);
$row = $db->loadObject();
}
// End of hack
In the same way, to find the first item as the next link in case the current item is the last category item, you will modify the getNextItem() method by adding this code snippet directly above the return $row;
line:
// Start of hack
if(is_null($row)){
// Get first item
if ($ordering == "0")
{
$query = "SELECT * FROM #__k2_items WHERE id < {$id} AND catid={$catid} AND published=1 AND ( publish_up = ".$db->Quote($nullDate)." OR publish_up <= ".$db->Quote($now)." ) AND ( publish_down = ".$db->Quote($nullDate)." OR publish_down >= ".$db->Quote($now)." ) {$accessCondition} AND trash=0 {$languageCondition} ORDER BY ordering ASC";
}
else
{
$query = "SELECT * FROM #__k2_items WHERE id != {$id} AND catid={$catid} AND ordering < {$ordering} AND published=1 AND ( publish_up = ".$db->Quote($nullDate)." OR publish_up <= ".$db->Quote($now)." ) AND ( publish_down = ".$db->Quote($nullDate)." OR publish_down >= ".$db->Quote($now)." ) {$accessCondition} AND trash=0 {$languageCondition} ORDER BY ordering ASC";
}
$db->setQuery($query, 0, 1);
$row = $db->loadObject();
}
// End of hack
Then save the file and test.
This hack is valid for most of K2 2.6.x and 2.7.x releases.
You can find the whole item.php file already modified on GitHub Gist
For questions and inquires, please contact me via Contact Us page or Twitter: @JoomReem
Thanks for Joe Campbell (@heyjoecampbell) who suggested this hack.