Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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 ) );
share|improve this answer
    
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 van Waveren Jun 9 '13 at 9:33
    
@RutgervanWaveren The global post object on a single page is available before you call the loop. –  toscho Jun 9 '13 at 9:35
    
Can you provide an example please? –  Damainman Oct 27 '13 at 0:22
2  
@Damainman See my update. –  toscho 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

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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