Last active
February 28, 2018 23:13
-
-
Save guytzhak/f5a19224970f5c400748e5c30a9d8aec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Save current single product to cookies | |
* To display those products in single product 'Recentrly searched' section | |
*/ | |
add_action('wp', 'matat_save_current_single_product_to_cookies'); | |
function matat_save_current_single_product_to_cookies() { | |
if( get_field('recently_viewed_cookie_num', 'options') ) { | |
$number_of_products = get_field('recently_viewed_cookie_num', 'options'); | |
} else { | |
$number_of_products = 10; | |
} | |
if( is_singular('product') ) { | |
global $post; | |
$product_id = $post->ID; | |
if( !matat_check_if_current_product_id_is_in_cookie( $product_id ) ) { | |
if( isset($_COOKIE['recently_viewed']) && !empty($_COOKIE['recently_viewed']) ) { | |
$cookie = $_COOKIE['recently_viewed']; | |
$products_array = unserialize( $cookie ); | |
$length = count( $products_array ); | |
echo $length; | |
echo '<br>'; | |
echo $number_of_products; | |
if ( $length <= $number_of_products ) { | |
$products_array[] = $product_id; | |
} else { | |
array_unshift( $products_array, $product_id ); | |
} | |
setcookie( 'recently_viewed', serialize( $products_array ), time() + 60 * 60 * 24 * 30 ); // set cookie for 30 days | |
} | |
} | |
} | |
} | |
/* | |
* Check if current product id include within the cookies for 'recently searched' section | |
*/ | |
function matat_check_if_current_product_id_is_in_cookie( $product_id ) { | |
if( isset($_COOKIE['recently_viewed']) && !empty($_COOKIE['recently_viewed']) ) { | |
$cookie = $_COOKIE['recently_viewed']; | |
$products_array = unserialize( $cookie ); | |
if( in_array( $product_id, $products_array ) ) { | |
return true; | |
} else { | |
return false; | |
} | |
} else { | |
$products_array = []; | |
setcookie( 'recently_viewed', serialize( $products_array ), time() + 60 * 60 * 24 * 30 ); // set cookie for 30 days | |
return false; | |
} | |
} | |
/* | |
* get products from cookie | |
*/ | |
function matat_get_recently_viewed_from_cookie() { | |
if( isset($_COOKIE['recently_viewed']) && !empty($_COOKIE['recently_viewed']) ) { | |
$cookie = $_COOKIE['recently_viewed']; | |
$products_array = unserialize( $cookie ); | |
return $products_array; | |
} else { | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment