3

I have a Wordpress website which I set a cookie using the jQuery cookie plugin.

This is my JS code in the end of one of my wordpress landing pages which sets a cookie using Javascript/jQuery - AND WORKS:

<script type="text/javascript" src="https://example.com/wp-content/themes/themeeee-child/js/jquery.cookie.js"></script>
<script type="text/javascript">

// Parse the URL
var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};

// Give the URL parameters variable names
var source   = getUrlParameter('utm_source');
var medium   = getUrlParameter('utm_medium');
var term     = getUrlParameter('utm_term');
var content  = getUrlParameter('utm_content');
var campaign = getUrlParameter('utm_campaign');

// Setting Cookie using jQuery 
if(jQuery.cookie('utm_source') == null || jQuery.cookie('utm_source') == "") {
  jQuery.cookie('utm_source', source); 
}
if(jQuery.cookie('utm_medium') == null || jQuery.cookie('utm_medium') == "") {
  jQuery.cookie('utm_medium', medium); 
}
if(jQuery.cookie('utm_campaign') == null || jQuery.cookie('utm_campaign') == "") {
  jQuery.cookie('utm_campaign', campaign); 
}
if(jQuery.cookie('utm_term') == null || jQuery.cookie('utm_term') == "") {
  jQuery.cookie('utm_term', term); 
}
if(jQuery.cookie('utm_content') == null || jQuery.cookie('utm_content') == "") {
  jQuery.cookie('utm_content', content); 
}

// Set a flag 
jQuery.cookie('coo_flag', 1, { expires : 365 }); 


</script>

enter image description here

$_COOKIE['coo_flag'] is set to "1" now.

On a total different page, at the bottom of the template file, I have this code part that checks using PHP if the $_COOKIE['coo_flag'] is set, and if is true, it fires a google pixel script:

<?php 

  // session_start();
  if ( $_COOKIE["coo_flag"] ) {
    echo $_COOKIE["coo_flag"];
?>

<!-- Google Code for Contact Us Registration Conversion Page -->
<script type="text/javascript">
  /* <![CDATA[ */
  var google_conversion_id = 666;
  var google_conversion_language = "en";
  var google_conversion_format = "3";
  var google_conversion_color = "666";
  var google_conversion_label = "666";
  var google_remarketing_only = false;
  /* ]]> */
</script>
<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/conversion/666/?label=666&amp;guid=ON&amp;script=0"/>
</div>
</noscript>

<?php 
  } else {
    echo "false";
     var_dump($_COOKIE["coo_flag"]);
  }
?>

and I keep getting this output result:

falseNULL

I have been trying to get it using JS too:

<script type="text/javascript" src="https://yellowheadinc.com/wp-content/themes/sogo-child/js/jquery.cookie.js"></script>

<script type="text/javascript">

var cookieValue = jQuery.cookie("coo_flag");
console.log(cookieValue);

</script>

and got no output for console.log(cookieValue);

Please help me find the proper way to get the cookie variable.

[01.02.2017]: More enlightenment:

  • A few days after saving the cookie for a year (view screenshot), I noticed it vanished from there (and I didn't clear my cookies!!!!).

  • Running the page without the "if" statement and just echoing the cookie doesn't work - both on Chrome and Firefox.

  • An edit to @Björn M:

enter image description here

Imnotapotato
  • 5,308
  • 13
  • 80
  • 147
  • 1
    When you say it's on a completely different page, do you mean a different domain? Cookies can't be used across domains. I'm guessing not, but figured I'd ask. – akousmata Jan 30 '17 at 17:59
  • www.example.com/contactus and www.example.com/about - same domain ;) – Imnotapotato Jan 30 '17 at 18:05
  • I hate to say it but I would put together an even more slimmed down version to test with. Take out all the HTML code in between your PHP tags and test from there. If you still can't set a cookie on one page and retrieve on another then there's something else going on with WP cause that's how it should work out of the box. – akousmata Jan 30 '17 at 20:06
  • Perhaps this? http://stackoverflow.com/questions/31748884/jquery-cookie-undefined-on-the-line-after-setting-it – akousmata Jan 30 '17 at 20:07
  • @akousmata I edited the main post. I tested all you have suggested and there are no positive results. – Imnotapotato Feb 01 '17 at 11:42
  • 1) Why do you set the cookie with jQuery instead of PHP? Could you give the details of the set cookie taken from the Developer Console of your browser? 3) Cookies are not only domain, but also possibly path specific. – Björn Feb 01 '17 at 11:46
  • 1. When setting this `setcookie("TestCookie", 1, time()+3600, '/');` for example I get this error output: `Warning: Cannot modify header information - headers already sent by (output started at /home/example/public_html/wp-content/themes/theme-new-child/header.php:3) in /home/example/public_html/wp-content/themes/theme-new-child/page-lp.php on line 1708`. - 2. See edited post :) - I am exactly testing the path thing, although if you figure i made something wrong with setting it via php i will be happy to know how to set this using PHP rather than loading a JS library. @BjörnM – Imnotapotato Feb 01 '17 at 12:16
  • 1) See my answer below. You can solve the jQuery problem by giving `/` as the explicit cookie path. 2) I see. You would need to create the cookie inside header.php or switch to `buffered output` http://stackoverflow.com/questions/2832010/what-is-output-buffering – Björn Feb 01 '17 at 12:21
  • @BjörnM 2. For example - adding an 'if' statement in the header "if this is template 'x' => setcoockies(...)" Would that work? Why it doesn't work from within the page? I have no idea what's `buffered output` but i will research thank you! – Imnotapotato Feb 01 '17 at 12:26

1 Answers1

2

Jquery Cookie creates cookies with a path in addition to the domain:

path path: '/' Define the path where the cookie is valid. By default the path of the cookie is the path of the page where the cookie was created (standard browser behavior). If you want to make it available for instance across the entire domain use path: '/'. Default: path of page where the cookie was created.

A cookie for path /abc is not visible to a page on path /def even though both pathes are on the same domain. Giving the cookie the root path / as quoted above should do the trick.

Björn
  • 471
  • 10
  • 15
  • Works! The path was the part that was missing. Anyway, I will be more than happy if you would maybe know why I kept getting this error saving this coockie with PHP. I definitely prefer using PHP rather than loading a whole jQuery cookie library. – Imnotapotato Feb 01 '17 at 12:23
  • See the comment above. You may not send header fields, e.g. `Cookie: ` after you started serving content, e.g. ``: http://stackoverflow.com/questions/2832010/what-is-output-buffering – Björn Feb 01 '17 at 12:24
  • Thank you so much! – Imnotapotato Feb 01 '17 at 12:26
  • Well maybe output buffering is no good idea in WP after all: https://wordpress.org/support/topic/recommended-php-output-buffering-setting/. Probably you should just move the cookie creation to header.php. – Björn Feb 01 '17 at 12:29
  • I have just noticed an other following problem as mentioned before: `A few days after saving the cookie for a year (view screenshot), I noticed it vanished from there (and I didn't clear my cookies!!!!).` I closed the browser and re-opened it - the cookies are gone! – Imnotapotato Feb 01 '17 at 12:39
  • I guess that the attribute `expires` takes a timestamp or something similiar. If this http://stackoverflow.com/questions/14939994/jquery-cookies-set-expire-time does not do the trick please open a new question as it has nothing to do with the path topic. Cheers, mate. – Björn Feb 01 '17 at 12:51