What is wrong with this code?
Code detects that user is coming from the expected referral site and adds cookie, but upon page refresh the code does not see the cookie and runs the !isset code and recreates the cookie again. not sure why. any ideas?
Just trying to insure that if its the right referral site, then create the cookie so that that user can use the entire site since they have a cookie and access now is on the cookie and not http_referrer.
below code is in functions.php in child theme and runs under init hook, so it runs on each page. That is what I was told was best.
add_action('init', 'bbb_referral_check' );
function bbb_referral_check() {
if (!is_admin()){
$allowed_host = 'bbb.com';
$theurl = $_SERVER['HTTP_REFERER'];
//$theurl = wp_get_referrer();
$host = parse_url($theurl, PHP_URL_HOST);
$ishost = false;
if (strpos($host, $allowed_host) !== false) { $ishost = true; }
$javascript_ouput = "<script>console.log('Debug Info: " .$ishost. "');
</script>";
echo $javascript_ouput;
//echo "The allowed host: ".$allowed_host; exit;
if ( !isset($_COOKIE["bbb-referral"])) {
$javascript_ouput = "<script>console.log('Debug Info cookie not set: ');</script>";
echo $javascript_ouput;
if ($ishost)
{
$javascript_ouput = "<script>console.log('Debug Info is host
match: " .$host. "');</script>";
echo $javascript_ouput;
setcookie( "bbb-referral", "bbb-referral", time() + 1800, COOKIEPATH, COOKIE_DOMAIN);
} else {
$javascript_ouput = "<script>console.log('Debug Info not host match: " .$host. "');</script>";
echo $javascript_ouput;
//Redirect
wp_redirect('http://bbb.com' ); exit;
}
}//isset
$javascript_ouput = "<script>console.log('Debug Info cookie is set: ');</script>";
echo $javascript_ouput;
}//admin
}//function