1

I'm trying to make a splash screen appear only the first time someone visits a Wordpress site. I don't know much about PHP but setting and reading a cookie seemed like an easy way to do this, so I added this to the header.php:

<?php if ( !isset($_COOKIE['accessed']) ) { 
    setcookie('accessed', 'yes', time() + (86400 * 30)); // 30 days
?>
    <script>
        // Some code
    </script>
<?php 
    } 
?>

The script runs but the cookie never get's set so it runs on every visit...

I read somewhere that you can't set and read a cookie on the same page with PHP, but if that's true then I really don't know how should I implement this.

Any hint would be really appreciated!

wabisabit
  • 412
  • 5
  • 16

2 Answers2

1

You need to send the cookie BEFORE the headers will sent.

In Wordpress, if you just put that code in your theme html, it will not work.

You need to do something like this in your functions.php file

function checkAccessed(){
        if ( !isset($_COOKIE['accessed']) ) { 
            setcookie('accessed', 'yes', time() + 3600*24*30); 
            define("ACCESSED", false);
        }else{
            define("ACCESSED", true);
        }
}
add_action("init", "checkAccessed");

and then in your theme html..

<?php if(!ACCESSED){ ?>
  <script></script>
<?php } ?>
0

It could be possible that the cookie is a path cookie. So basically that cookie will be sent only to a single page.

Do you have firebug? If you do try the 'Cookies' tab to check that. Then you can use the 'Network tab to double check that the cookie was actually sent by your users' browser.

Try this, changed the calculation for the time - not sure if it makes a difference but that's how I calculate 30 days:

<?php if ( !isset($_COOKIE['accessed']) ) { 
setcookie('accessed', 'yes', time() + 3600*24*30); // 30 days
?>
    <script>
    // Some code
    </script>
<?php 
    } 
?>
Zach C
  • 61
  • 1
  • 9
  • Try temporarily removing the !isset lines with a // comment out. Just to test. – Zach C Sep 11 '13 at 21:19
  • 1
    Also I believe the 30 days behind your setcookie function may be causing an issue, just noticed that. – Zach C Sep 11 '13 at 21:21
  • I tried commenting and no change. The *30 days* part is actually commented in my code, I messed up while copying it here. – wabisabit Sep 11 '13 at 21:26
  • Tried editing the time calculation, see the code above. Not sure if that might be an issue but that's how I use it in my code. – Zach C Sep 11 '13 at 21:30
  • Nope... I just tried this in isolation and it works, so it must have something to do with how Wordpress works. Thanks for the help anyways! – wabisabit Sep 11 '13 at 21:36