I have a tricky situation….
I’d like to check for a cookie. If it doesn’t exist then then redirect to an internal wordpress page, and set a cookie. And then carry on browsing the site. But i get stuck in a loop if the url doesn’t exist. This is what i have so far…any help would be great.
function cookiebasedredirect() {
// WHEN YOU HAVE FOUND YOUR COOKIE
if ( !isset($_COOKIE["sevisitor"])) {
setcookie('sevisitor', 1, time()+1209600, "https://wordpress.stackexchange.com/", "http://localhost/child/", false);
// GRABS THE CURRENT PAGE NAME - THIS IS ALSO KNOWS AS THE PAGE/POST SLUG
$pagename = get_query_var('pagename');
// PAGE CHECK SO THAT YOU ARE NOT IN AN INFINITE LOOP
// IN THIS SAMPLE MEDIA-GALLERIES IS THE PAGE YOU WANT TO BE
// REDIRECTED TO IF A COOKIE IS NOT SET, BUT ONCE YOU GET THERE
// MAKE SURE WORDPRESS DOESN'T EXECUTE THE REDIRECT
if( $pagename != "about-myself") {
wp_redirect( get_site_url().'/about-myself' ); exit;
} else {
}
} else {
}}
add_action("template_redirect", "cookiebasedredirect");
2 Answers
why not use the init
action hook:
function has_my_cookie()
{
if (!is_admin()){
//Check to see if our cookie is set if not redirect to your desired page and set the cookie
if ( !isset($_COOKIE["sevisitor"])) {
//setcookie
setcookie('sevisitor', 1, time()+1209600, "https://wordpress.stackexchange.com/", "http://localhost/child/", false);
//Redirect
wp_redirect( get_site_url().'/about-myself' ); exit;
}
}
}
add_action('init', 'has_my_cookie');