I run a wp_query that fetches 4 posts from db with rand()
and displays them in a grid to visitors.
What I need is to display the exact same posts the query fetched the first time, a second time to the same visitor, based on their interaction with the site.
But if I run a new query, it will just pick random posts again. Everything works on the site, the query does what it is supposed to.
But how do I store the first custom wp_query in a cookie or session in order to display the same posts again to the same visitor?
Is it best to store the post ID's and fetch them later via the cookie or how is it done?
I run a wp_query that fetches 4 posts from db with rand()
and displays them in a grid to visitors.
What I need is to display the exact same posts the query fetched the first time, a second time to the same visitor, based on their interaction with the site.
But if I run a new query, it will just pick random posts again. Everything works on the site, the query does what it is supposed to.
But how do I store the first custom wp_query in a cookie or session in order to display the same posts again to the same visitor?
Is it best to store the post ID's and fetch them later via the cookie or how is it done?
If the function is called on the same page (during the same request), you don't have to store it in COOKIE nor SESSION.
All you need is to create global variable and store the query in that variable. This way you won't send them to user and won't have to store them in visitors browser.
So you can write it like this:
// first call
global $my_special_query;
$my_special_query = new WP_Query(...);
...
// second call
// global $my_special_query; // if the second call is in another file, there is a chance you'll have to uncomment this line
if ( $my_special_query->have_posts() ) { ... }
But there are few things you'll have to remember:
the_post
in the first call, then the query will be already in that position in the second call. You can use rewind_posts
method to change that.$my_special_query
variable is a global one.If both calls are made in different requests, then you can't use a variable any more. So you'll have to store these posts in visitors browser.
Remember that using sessions/cookies cause some law problems in some countries and you'll have to deal with them. You can use either COOKIEs or SESSION to do this.