Advertisement
arsh999cg

Set Cookies for Recently viewed products

Dec 22nd, 2022
833
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.72 KB | None | 0 0
  1. <?php
  2. add_action( 'wp_footer', 'set_recently_viewed_products_cookie' );
  3. function set_recently_viewed_products_cookie() {
  4.   if ( ! is_product() ) {
  5.     return;
  6.   }
  7.   global $post;
  8.   if ( isset( $_COOKIE['recently_viewed_products'] ) ) {
  9.     $viewed_products = (array) explode( '|', wp_unslash( $_COOKIE['recently_viewed_products'] ) );
  10.     if ( ! in_array( $post->ID, $viewed_products ) ) {
  11.       $viewed_products[] = $post->ID;
  12.     }
  13.     if ( count( $viewed_products ) > 15 ) {
  14.       array_shift( $viewed_products );
  15.     }
  16.   } else {
  17.     $viewed_products = array( $post->ID );
  18.   }
  19.   // Set (or renew) the cookie
  20.   setcookie( 'recently_viewed_products', implode( '|', $viewed_products ), time() + MONTH_IN_SECONDS, '/' );
  21. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement