1

I cannot get a cookie to set properly through WordPress theme. I am putting the following code on the bottom of my functions.php page for my theme.

function set_cookie() {
if (isset($_GET['id'])) {
    $referrerID = $_GET['id'];
        setcookie('referrerid', $referrerID,time()+ 3600 * 24, COOKIEPATH, COOKIE_DOMAIN, false);
    }
}
add_action( 'init', 'set_cookie');

I even went as far as using JavaScript to alert if the script reached the function (which it did).

Why are my cookies not being set?? (The code works locally - outside of WordPress that is).

2 Answers 2

3

Make sure the HTTP headers are not sent already at the point you want to set the cookie. Here's how you can test that:

function set_cookie() {
  var_dump(headers_sent()); // should be bool(false)
  ...

Turning WP_DEBUG on in your config.php file may help also while debugging.


By the way, you really should be doing some filtering on $_GET['id']. This variable could contain anything. Casting it to a (positive) integer should go a long way:

$referrerID = absint($_GET['id']); // Note: absint() is a WP function
9
  • I can place that function anywhere and how will it let me know the results? Does it echo the information back?
    – Evan
    Commented Jan 19, 2012 at 13:25
  • Yes, var_dump() echoes its output.
    – Geert
    Commented Jan 19, 2012 at 14:04
  • it returned bool(false) - the cookie is still not being set though. Is there any way we could do a private chat if you have a free minute?
    – Evan
    Commented Jan 19, 2012 at 14:05
  • Not possible now. Could you inspect the HTTP response headers? Look for the Set-Cookie header.
    – Geert
    Commented Jan 19, 2012 at 14:15
  • What would be the best way to go about retrieving such headers? I used this code just now but I don't think it's what you were looking for: foreach (getallheaders() as $name => $value) { echo "$name: $value\n"; }
    – Evan
    Commented Jan 19, 2012 at 14:21
1

Another option is to use PHP's ob_start(); and ob_end_flush();.

You can find documentation on the two functions here

The way I resolved my issues was to call the two functions before and after the opening and closing html tags like this:

<?php ob_start(); ?>
<!DOCTYPE html>
<html>
  <head>
  </head>
<body>
  <?php /* Wordpress loop and other tempate code here */ ?>
</body>
</html>
<?php ob_end_flush(); ?>

The issue I was running into was calling a global function that used PHP's setcookie(); and because WordPress processes the page progressively, the cookie couldn't be created due to the page's headers already being sent.

PHP's output buffering function forces the headers to be sent before WordPress processes the page.

Hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.