0

I have a blog index page which only lists 1 custom post at a time on the index page (it is paginated). I am trying to get the ID of that post from outside the loop (in the footer, after the loop) but am unable to do so. When I call it, i get the ID of the next post not the current one.

global $post;
echo $post->ID;  // return ID of the next post, not the current one. not sure why.

I know that this is an unusual setup (my index page is basically a single post page). Should I change my index page design, or is there a simple way for me to just get the current post ID without throwing away all my current work?

  • It feels like a bit of a hack but you could store the post ID in a global variable in your loop and read that variable from the footer. – Rup Jun 29 '20 at 14:03
  • 1
    The reason it is happening: the_post() iterates the index in the array of posts being looped. developer.wordpress.org/reference/functions/the_post – jdm2112 Jun 29 '20 at 15:09
  • 1
    Try using get_previous_post() developer.wordpress.org/reference/functions/get_previous_post. That will return the whole post object though so $var->ID to get the ID. – jdm2112 Jun 29 '20 at 15:10
  • 1
    thanks. it's an odd solution, but i understand why (thanks for the reference link) – Gaurav Jun 30 '20 at 15:49
  • 1
    thanks @jdm2112 - in the end i decided to refactor the code differently so that i make the call inside the loop instead. makes it neater. – Gaurav Jul 3 '20 at 5:38

Your Answer

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

Browse other questions tagged or ask your own question.