Allow guests to save favourite pages?

We’re creating a site where we want guest users to add pages to a favourites list (post IDs), so they can print or email their selection if they want.

What would the best way be to do this in WordPress? I think ajax but I’m not too sure how to save it in the WordPress framework.

2 Answers
2

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