0

I'm trying to set a cookie when a user is on a single post. I'm keeping track of how many single posts he has read this month. I have two problems:

I have a custom template and added the following code to my functions.php

function articlesVisited() {
  if (is_single()){
    $postNumber = $wp_query->post->ID;
    setcookie($postNumber,'visited',time()+60*60*24*31);
  }
}
add_action('init', 'articlesVisited');

First. The code inside is_single() is never reached when I visit a single post on my site. If I put an -else- block after it, it executes that.

Second, the $wp_query->post->ID does not give me the ID of the post. I think that has something to do with global variables...

Does anyone has experience with this?

3

init is too early (it happens before the main query), use the action template_redirect instead.

And for the ID use get_the_ID().

Example:

if ( is_singular() )
    setcookie( get_the_ID(), 'visited',time() + ( DAY_IN_SECONDS * 31 ) );
  • Changing to template_redirect helped! Thanks! Also now $wp_query->post->ID works, I used this because get_the_ID() only worked within the Loop if I'm correct. – Rutger Jun 9 '13 at 9:33
  • @RutgervanWaveren The global post object on a single page is available before you call the loop. – fuxia Jun 9 '13 at 9:35
  • Can you provide an example please? – Damainman Oct 27 '13 at 0:22
  • 2
    @Damainman See my update. – fuxia Oct 27 '13 at 0:26
  • Awesome thanks, and just template_redirect instead of init? Thank you again, I upvoted you. – Damainman Oct 27 '13 at 0:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.