How to store post ID’s in cookie or session to display the same posts later

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:

  1. The query will remember its state. So if you call 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.
  2. If second call is in another PHP file, there is a chance you’ll have to tell PHP that this $my_special_query variable is a global one.

On the other hand…

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.