Skip to content

Instantly share code, notes, and snippets.

@simplethemes
Last active April 10, 2017 22:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simplethemes/4f9b6f969bcc0a0a6668aeed75491a15 to your computer and use it in GitHub Desktop.
Save simplethemes/4f9b6f969bcc0a0a6668aeed75491a15 to your computer and use it in GitHub Desktop.
/*
Plugin Name: Set Shop Cookie
Description: Adds a cookie for most recently viewed products
Version: 0.1
Author: Casey Lee
Author URL: https://simplethemes.com
*/
class SetWpShopCookie {
/**
* @var string API URL
*/
public static $instance;
public $recent_cookie;
public $cookie_name = 'recent';
public $recent_products;
/** Hook WordPress
* @return void
*/
public function __construct()
{
self::$instance = $this;
add_action( 'template_redirect', array( $this, 'get_recent_cookie') );
add_action( 'template_redirect', array( $this, 'set_post_cookie') );
add_shortcode( 'recently_viewed', array( $this, 'recent_products') );
}
/**
* Gets the 'recent' cookie
* @return array or null
*/
public function get_recent_cookie()
{
$recent_cookie = null;
$cookies = array();
foreach ( $_COOKIE as $name => $value ) {
$cookies[] = new WP_Http_Cookie( array( 'name' => $name, 'value' => $value ) );
}
foreach($cookies as $cookie) {
if ($this->cookie_name == $cookie->name) {
$recent_cookie = $cookie;
break;
}
}
$this->recent_cookie = $recent_cookie;
}
/**
* Load scripts when plugin is executed
* @see https://developer.wordpress.org/reference/classes/wp_http_cookie/
*/
public function set_post_cookie()
{
global $post;
$product_id = $post->ID;
$cookie_time = time() + 60 * 60 * 24 * 7;
// nothing to do here if we're not in a product single
if (!is_product())
return;
// create the cookie
if(!$this->recent_cookie) {
$data = array();
array_unshift($data, $product_id);
setcookie($this->cookie_name, serialize($data), $cookie_time, COOKIEPATH, COOKIE_DOMAIN);
// update existing cookie
} else {
$data = unserialize($this->recent_cookie->value);
if(!in_array($product_id, $data)) {
array_unshift($data, $product_id);
if(count($data) > 8) {
array_pop($data);
}
// Use WP globals for portable cookie settings
setcookie($this->cookie_name, serialize($data), $cookie_time, COOKIEPATH, COOKIE_DOMAIN);
}
}
// Debug
// var_dump($this->recent_cookie);
}
// Recently viewed products shortcode
function recent_products( $atts ) {
// Attributes
$atts = shortcode_atts(
array(
'count' => '5',
),
$atts,
'recently_viewed'
);
$product_data = unserialize($this->recent_cookie->value);
$str = '';
if ($product_data) {
foreach ($product_data as $products_viewed) {
$str .= $products_viewed .' ,';
}
return 'You recently viewed these products: ' . rtrim($str,',');
} else {
return 'Why don\'t you visit our shop?';
}
}
}
new SetWpShopCookie;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment