Setting cookies

Cookies used in web applications have been percieved by the public as something not to be trusted. Fortunately they can be used by developers to deliver better expereinces on your webiste. For example somone visitng and returning we can display the last products they were viewing or a category they were interested in.

In this tutorial I show you how I used cookies to display the last 3 products viewed inside of WordPress. This could be applied in any situation though. In thi sexample we are focused on first-party cookies are directly created by the website you are using. These are generally safer, as long as you are browsing reputable websites or ones that have not been compromised.

function definerecentview() {  //get the last 3 products viewed
// declare $wpdb as a global variable using used in WordPress
global $wpdb
//Set the current product ID
//gets product id from URL that was viewed
$currentProduct = intval($_GET['singleProduct']);
add_action('init', 'definerecentview'); //Fires after WordPress has finished loading but before any headers are sent.
//Set default of viewed products to an empty array
$viewed_products = array();
//If there is already a saved cookie value then uses it
$viewed_products = (array) explode( ',', $_COOKIE['recently_viewed']);
//If the current product exists in the array remove it
if(in_array($currentProduct, $viewed_products))
unset($viewed_products[array_search($currentProduct, $viewed_products)]);
//Add the current product to the end of the array
$viewed_products[] = $currentProduct;
//Ensure length of elements in the array is not greater than 3 items
if (sizeof( $viewed_products ) > 4 ) {
array_shift( $viewed_products );