Here is an attempt at cookie creation within header.php of a theme file.
For some reason the cookie keeps disappearing. I was wondering if anyone can spot the error here (or even suggest a simplified way to do this).
I end it all using shortcode so i can output [show_the_code] in a post/page. The problem is that the cookie gets written but doesn't persist. Also, I am using session in case some doofus doesn't have cookies enabled (it happens).
Help me on this and I will definitely owe you a few beers :)
<?php
/*
* ID TRACKING AND CODE TRACKING
*
*/
//
// start a session
session_start();
//
// get ID and save to session ID
if(isset($_GET['sourceID'])) {
$_SESSION['sourceID']=(int)$_GET['sourceID'];
}
//
// code tracking
if(isset($_GET['theCode'])) {
$_SESSION['theCode']=(int)$_GET['theCode'];
}
//
// make a cookie
if(!isset($_COOKIE['sourceID'])) {
setcookie("nomSourceID", $_GET['sourceID'], time()+60*60*24*30); // 30 days
}
if(!isset($_COOKIE['theCode'])) {
setcookie("nomCode", $_GET['theCode'], time()+3600); // 1 hour code expiry
}
//
// create strings
function show_the_code(){
if (isset($_COOKIE['nomCode'])){
echo"this is the cookie value";
return $_COOKIE['nomCode'];
} else {
echo"this is the session value";
return $_SESSION['theCode'];
}
}
add_shortcode('show_the_code', 'show_the_code');
?>