I have a session array which functions to store the IDs of posts from the accessories
post type. The purpose of this is to achieve a "recently viewed posts" block.
So, when someone clicks into a post that belongs to the accessories
post type, it will store that ID into the session array. Then, in the arguments for the query, I’m just passing the array variable.
Issues:
- I’m accessing my local site on another machine and the array is returning the same results as they were on my other machine. I don’t want users to see the same stuff
- After 24 hours, I want the session to destroy itself (reset itself). However, it’s been a few days and the session is still active.
At the very top of header.php
I have defined my session:
<?php
session_start();
// Check if the session variable exists
if(!isset($_SESSION['recently_viewed'])){
// if it doesn't, create an empty array
$_SESSION['recently_viewed'] = array();
}
// if accessories post type, then get ID and add to array
if ( is_singular ( 'accessories' ) ):
global $post;
$current_post_id = $post->ID;
if ( !in_array ($current_post_id, $_SESSION['recently_viewed']) ):
$_SESSION['recently_viewed'][] = $current_post_id;
endif;
endif;
// destroy session after 24 hours
if( !isset($_SESSION['creationTime']) ){
$_SESSION['creationTime'] = time();
}
if (time() - $_SESSION['creationTime'] <= 60*60*24 ){
// still today
} else {
session_destroy();
}
?>
Then, the arguments I’m running are:
<?php
$args = array(
'post_type' => 'accessories',
'post__in' => $_SESSION['recently_viewed'],
'posts_per_page' => '5',
'post_status' => 'publish',
'order' => 'ASC'
);
?>
Any ideas why I’m facing those issues?
3
Answers
When you run this code all the users of the session are disconnected and redirected to the page chosen here login.php
check
$_SESSION['recently_viewed']
value that you correctly add accessories item to array. Maybe your mistake is some other where. Shortly your codes seems correct to me.Also be sure that are you really eliminate
$_SESSION['recently_viewed']
array values from your query conditions…