Allow guests to save favourite pages?

Cookies, or even HTML5 local storage, seem like a good way to implement this. Here’s some basic code that could serve as a starting point. Post IDs are stored as CSV in the cookie.

// Load current favourite posts from cookie
$favposts = (isset($_COOKIE['favposts'])) ? explode(',', (string) $_COOKIE['favposts']) : array();
$favposts = array_map('absint', $favposts); // Clean cookie input, it's user input!

// Add (or remove) favourite post IDs
$favposts[] = $post->ID;

// Update cookie with new favourite posts
$time_to_live = 3600 * 24 * 30; // 30 days
setcookie('favposts', implode(',', array_unique($favposts)), time() + $time_to_live);

Leave a Comment