Support » Plugins » Hacks » Having trouble setting a cookie within wordress.

  • Hi, I hope I have more luck posting the topic here.
    My original post states that I’m trying to code a hit counter which counts only unique views to the site. I’m trying to set a cookie with a 1hr expiry.
    My code:

    $file = (TEMPLATEPATH."/count.txt");
    $count_unique = 1;
    $cn = 'gcc';
    $count = intval(trim(file_get_contents($file)));
    if ($count_unique == 0 || !isset($_COOKIE[$cn])) {
       ++$count;
       file_put_contents($file, $count);
       setcookie($cn, '1', time()+3600, '/','.localhost');
    }
    echo $count;

    That only works outside of wordpress (excluding the template path constant) so I changed my setCookie accordingly:
    setcookie($cn, 1, time()+3600, COOKIEPATH, COOKIE_DOMAIN);

    Still no luck. Please help if you know an answer.
    Thanks in advance.

Viewing 2 replies - 1 through 2 (of 2 total)
  • 2 weeks later and the fix was very simple.

    Move the cookie code to the functions.php, add an action to the ‘init’ then output the results in the footer.

    Unfortunately it isn’t working as originally thought. – PLEASE help 🙂
    After 3 weeks of the site being live they have a huge hit count but no real traffic to justify this – I started observing google analytics side-by-side with much smaller results.

    Here is the code that I have in the functions.php:

    function writecookies() {
       $file = (TEMPLATEPATH."/log.dat");
       $count_unique = 1;
       $cn = 'gacc';
       $count = intval(trim(file_get_contents($file)));
       if ($count_unique == 0 || !isset($_COOKIE[$cn])) {
          ++$count;
          file_put_contents($file, $count);
          setcookie( $cn, $cn, time()+43200, COOKIEPATH, COOKIE_DOMAIN, false, false);
       }
    }
    add_action('init','writecookies');

    What am I doing wrong with the code? Am I calling the wrong hook? Am I recording all spiders as visitors? Should I not be using php for the hit counter and instead maybe use javascript?

    ANY small hints in the right direction would be greatly appreciated, or even an answer.
    Thanks!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Having trouble setting a cookie within wordress.’ is closed to new replies.