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?

1 Answer 1


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 ) );
  • 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, 2013 at 9:33
  • @RutgervanWaveren The global post object on a single page is available before you call the loop.
    – fuxia
    Jun 9, 2013 at 9:35
  • Can you provide an example please?
    – Damainman
    Oct 27, 2013 at 0:22
  • 2
    @Damainman See my update.
    – fuxia
    Oct 27, 2013 at 0:26
  • Awesome thanks, and just template_redirect instead of init? Thank you again, I upvoted you.
    – Damainman
    Oct 27, 2013 at 0:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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