Hello, I try to set two cookies every time a user visit blog' posts, in order to save the last two visited posts by same user. With this information I have to display in a home section these two last posts, so they well be different for each user. If is first visit I will display two random posts.
I have set a function hooked to init hook that set the two cookies every time the user is visiting a post. But I have some different problems that I can't figure how to resolve on my own.
As in the init hook it is not yet loaded the current post information and neither the is_single function or is_home function, I can't know which page the user is, so I have to take the server url with $_SERVER["REQUEST_URI"]. My function writed in functions.php
1) First problem is if I try to refresh header after setting the cookies. This code is getting ok without the header("refresh:0"), but with the refresh is looping all time and not loading the page, like if exit not running.
function enn_set_cookies() {
if (!isset($_COOKIE['last_ing_post'])) :
setcookie('last_ing_post', sanitize_text_field(htmlspecialchars( $_SERVER["REQUEST_URI"], ENT_QUOTES, 'UTF-8' )), time() + 86400, "/");
header("Refresh:0");
exit;
else :
setcookie('last_ing_post', sanitize_text_field(htmlspecialchars( $_SERVER["REQUEST_URI"], ENT_QUOTES, 'UTF-8' )), time() + 86400, "/");
setcookie('prelast_ing_post', sanitize_text_field($_COOKIE['prelast_ing_post']), time() + 86400, "/");
header("Refresh:0");
exit;
endif;
}
add_action( 'init', 'enn_set_cookies' );
2) Same code without refressing header is running ok if the user is navigating between posts, but if the user goes to pages or home, then I would need to know if the page is home. The home is getting posts in a general wp_query that are loading with ajax_infinite_scroll. When I set the cookie for home page, it is writing a big string that begins like this:
Value %2Fwp-admin%2Fadmin-ajax.php%3Faction%3Dalm_query_posts%26amp%3Bquery_type%3Dstandard%26amp%3Bnonce%3D9465c1cf3b.....
I don't know how to distinguish if is a page or archive page, but I can try to know if is home by getting only "/" or try strpos if is wp_admin inside the cookie. But if I try this:
$url = $_SERVER["REQUEST_URI"];
$ishome = strpos($url, "wp_admin");
if($ishome === false) {
// if not is home we do our stuff (but we dont know if is a page, so her we have another problem ;
do set cookies
} else {
//if is home we dont touch our cookies, so they remain set with last pots or, if is first time, they remain unset
}
the variable $ishome never is false, because the strpos never return false as if in the cookie there isn't the "wp_admin" string, but there is it.
Maybe there is another approach to the whole goal I need to achieve, but I can't figure how. Iy anyone has any idea It will be very much appreciated.