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!

有帮助吗?

解决方案

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 } ?>

其他提示

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 
    } 
?>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top