An easy way to handle previous and next product links

I’m working on a custom eCommerce site for a customer right now, and ran into an issue– they wanted to have, on every product page, a forward and back button to get to the previous and next items. The problem with this is that they may have arrived on the product page in a couple of different ways, through search or browsing, with different criteria set.

I came up with this easy routine which goes through the result set, whether it’s search result or category view, then creates an array where the key is the current product ID, and the values are the IDs of the product before and the product afterward. So if I’m on product 157, $ordering[157][‘next’] will give me the ID of the next product. Just pop it in a session, and you’re good to go.

Simple and straightforward– feel free to reuse all you like!


foreach($results as $row) {
/////////////////////////////////////////////////////////////////////
// so that we can capture previous, current, and next, we're going
// to process one row behind, so for the first row, don't put anything into
// our array
/////////////////////////////////////////////////////////////////////
if(!$curr) {
$curr = 'first';
$next = $row['id'];
} else {
// Everything moves back one space
$prev = $curr;
$curr = $next;
$next = $row['id'];
// It gets saved into the array
$ordering[$curr]['prev'] = $prev;
$ordering[$curr]['next'] = $next;
}
}
// Here we're handling the last row
$ordering[$next]['prev'] = $curr;
$ordering[$next]['next'] = 'last';

Leave a Reply

Your email address will not be published. Required fields are marked *