set cookie in theme header.php based on page – wordpress

I’m trying to set a cookie in my wordpress theme header.php file.

I’ve found a bit of information about this but it all seems to use the functions.php file, this isn’t really an option for me as I’m setting the cookie based on the page.

Read More

I’m just wondering how I could go about doing this, or what a possible work around might be.

Here’s my code from my header.php file.

<?
// Set cookie
if (is_page('437')) {
  setcookie("DM", "mis", time()+31536000);
} else if (is_page('441')) {
  setcookie("DM", "w2p", time()+31536000);
}

echo $_COOKIE["DM"];
print_r($_COOKIE);

// Check cookie to load style
if (!is_front_page()){ 
  if (isset($_COOKIE["DM"])) {
    if ($_COOKIE["DM"] == "mis") { ?>
      <link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo('template_directory'); ?>/css/mis.css" />
  <? } else if ($_COOKIE["DM"] == "w2p") { ?>
      <link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo('template_directory'); ?>/css/w2p.css" />
   <? }
  }
}
?>

Related posts

Leave a Reply

1 comment

  1. Setting the cookie, queues it up to be sent to the client, but doesn’t add it to the $_COOKIE array. I believe the $_COOKIE array is only constucted and populated once–at the initial request time. Any cookie you want to get to goes to the client and is sent back in the following request for the next page and is then available.