WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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;
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
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().


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
@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


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.