$post->ID and the_id() always return the wrong value

All we need is an easy explanation of the problem, so here it is.

I have a site where I display the same exact footer on every page. There is one exception, though. On one certain page I need to change one small part of the footer.

I figure the simplest way to do this is to check, within the footer, whether I’m on that page or not. It wouldn’t make sense to change the whole entire footer for that page since I’m only changing a tiny part of the footer, deep within the footer.

The problem is that whenever I call $post->ID or the_id() from within the footer, it gives me an ID that clearly doesn’t match the post I’m on. It always gives me 89, no matter what page I’m on in the site.

I figure I must be doing something wrong. Can anyone tell me what it is?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

It sounds like you are altering the global $post data somewhere (usually another loop). Be sure to call wp_reset_postdata() after you are finished with something that sets up post data in an alternate loop.

Method 2

the_ID just echo the post , it doesn’t return the ID,
if you want the ID for the particular post ,

use <?php get_the_ID(); ?>

Method 3

It may be more reliable to test the status of $the_wp_query, which is the main query for the active page. The value of $post is simply whatever the last loop ended with, so you may have plugins affecting the value.

Method 4

Codex says (emphasis mine):

Displays the numeric ID of the current post. This tag must be within The Loop.

You try to use it in the footer, so failure is very well documented.

Let me suggest this: write a small plugin with its own post ID array (class member or uniquely named global; should be an array in order to deal with pages containing multiple posts).

Create a shortcode that adds the ID of the current post to this array. In the footer, you can read all IDs you need from it and you can be sure no one has tempered with them.

Method 5

My issue was I has assigning other values to the $post. I renamed $post to something else and it works.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply