I’m using PHP and I’m trying to keep an array of the last 10 post id’s in WordPress via $_SESSION array. I know I can add the latest post id like so:
$_SESSION['recently_viewed_posts'][] = $post->ID;
And similarly I could probably follow that command with something like this to remove ones greater than 10:
if( sizeof( $_SESSION['recently_viewed_posts'] ) > 10 )
{
array_shift( $_SESSION['recently_viewed_posts'] );
}
However this won’t work well if the user reloads the same post a few times, you could end up with something like:
Array
(
[recently_viewed_posts] => Array
(
[0] => 456
[1] => 456
)
)
Desired behavior:
- The last 10 post id’s will be keep in an array
- If a visited post is already in the array, it will move to the start or end of the array
- If the size of the array is 10 elements, and a new 11th post is visited, the oldest post id will be removed and the new post id added
I don’t care too much about what side of the array (start or end) the new posts are on, as long as it is consistent. I don’t really care what the array keys are.
What is the best way to accomplish this?
I tried searching for similar questions but didn’t come up with anything useful so I apologize if this is a dupe.
This pushes new entries onto the beginning of the array, weeds out duplicates using
array_unique(which keeps the first occurrence of an item) and limits the array to 10 entries. The most recent post will be at$_SESSION['recently_viewed_posts'][0].