Setting a redirect cookie in wordpress

I’ve been searching on the net for a solution to my problem all day, but I can’t make sense of anything I see, since I know absolutely NOTHING about coding.

What I’d like to do:

  1. I’d like to set a cookie when a person visits one particular page on my website, let’s call it Page 1.
  2. Then, when that visitor goes to another unrelated page (Page 2), he/she gets automatically redirected to Page 3 (because of the cookie that was set when they visited Page 1). Visitors without the cookie, don’t ever get to see Page 3.

What I’ve managed to do so far:

I’ve managed to SET the cookie in WordPress functions.php, by inserting the following:

function set_newuser_cookie() {
    if (!isset($_COOKIE['subscriber'])) {
        setcookie('subscriber', no, 0, COOKIEPATH, COOKIE_DOMAIN, false);
    }
}
add_action( 'init', 'set_newuser_cookie');

I’ve managed to define a redirect by inserting the following in functions.php:

if (!isset ($_COOKIE['subscriber']))
header ("Location: page2");
else
header ("Location: page3");

That’s as far as I’ve gotten. It doesn’t work because neither of the above are page-specific. I only want the cookie to be set (or variable changed) when the visitor visits one specific page, and then get redirected when he visits another specific page.

Is this doable?

Oh, and by the way, I’m on a self-hosted WordPress site.

Thanks so much.

Sammie

3 Answers
3

So the only part that is missing from your code is checking what page you are currently on. The is_page() function is a good way to get this context.

You could try it this way (I did not test it, only writeup out of my head to show the concept):

function set_newuser_cookie() {
    if (!isset($_COOKIE['subscriber']) && is_page('my-page-slug-page1')) {
        setcookie('subscriber', no, 0, COOKIEPATH, COOKIE_DOMAIN, false);
    }
}
add_action( 'init', 'set_newuser_cookie');

function my_cookie_redirect() {
   if (isset($_COOKIE['subscriber']) && is_page('my-page-slug-page2')) {
      wp_redirect('/page3');
      exit;
   }
}
add_action('template_redirect', 'my_cookie_redirect', 1);

The wordpress is_page() function either takes the page id, page slug or page_title as param.
http://codex.wordpress.org/Function_Reference/is_page

You should also always exit after an redirect, because otherwise the user would first load page-2 before beeing redirect to page-3

Leave a Comment