Reputation: 525
** UPDATE **
The code is working now. But Now I would like to have a div
display the sessions saved. This div is on the same page as the items and is called items
I tried using a refresh script. But this doesn't work.
Is this posible via jQuery or should I use AJAX (I'm not really "into" Ajax yet)...
Owke, lets see if I can explain this the best I can... I'm using Wordpress for a site I'm making now I would like to store the "liked" items a custom clicks.
So what I did was open a session in my header
<?php
session_start();
?>
Then on the page that needs to store the "like" I have the following code:
<?php
// Set session variables
$_SESSION["item"] = get_the_title();
?>
And where I would like to echo
it I placed this code:
<?php
if(isset($_SESSION['item'])){
echo $_SESSION['item'];
};
?>
This all works like it should, BUT there are multiple items a custom could like on one page. AND I would like to store all of them in my session. But it only stores 1 session at a time.
Do I need to work with numbers of prefixes, like item-x and item-y?
I found this bit of code: link
But because I'm using Wordpress and I just want the title I cant replace $apples, $oranges and $pears with your product ids. Because for me its just
<?php the_title(); ?>
So this, for me, won't work:
<?php
// Set session variables
$_SESSION["boot"] = array();
$_SESSION["boot"][] = the_title();
?>
Every time... how to get this to work?
Upvotes: 0
Views: 66
Reputation: 8945
To elaborate slightly on what was just said: $_SESSION[]
is an array which, like any other PHP array, stores arbitrary values under one or more "keys," such as "item"
.
Like any other PHP array, each value can be a single scalar, such as a book-title string or a single number, or it can be, itself, an array. (This is similar in concept to "a two-dimensional array.") Each of those array-keys could, in turn, lead to any other sort of information you wish to store: PHP data-structures can be arbitrarily deep, and PHP will store it all in your "session."
Now, if it were me, I would probably eliminate duplicates when I stored the values, so that I could be sure that the stored session information didn't contain duplicates at all. Thus, I wouldn't have to do anything special when I echo
ed them. Something like this:
$_SESSION["item"] = array_unique($_SESSION["item"]);
... exactly as I might do with any other PHP array.
Upvotes: 1
Reputation: 11375
You are overwriting your item
session every time. You need to make this an array.
$_SESSION["item"][] = get_the_title();
Now to echo
them, you want to get rid of duplicates, so use array_unique()
if(isset($_SESSION['item'])){
echo implode("<br />", array_unique($_SESSION['item']));
}
POC: https://repl.it/Cd7l
Upvotes: 1