I am developing a theme and I need to get the actual page ID, when I do:

global $post;
$thePostID = $post->ID;

I get the wrong ID. I tried get_the_ID() and I get the same ID that in the code above, but both are wrong. I also tried to do wp_reset_query() before getting the ID but I still get the same wrong ID. I am running the code above in a template and it is NOT inside of a loop.
I also want to clarify that I am trying to get a page ID, not a post ID, although the function seems to be the same.
What I am doing wrong and how could I fix it?

**Context

I have been testing the different suggestions and here I will try to clarify some. The template page that doesn’t show the right page ID displays the posts of a custom field that I created using ACF. The ID that I am getting when executing the_ID() or its variants is the first ID of the first post of the custom field. I retrieved the ID on the header of the template before executing any query and the result is the same, also when I reset the query the ID doesn’t change.

Any suggestions?

thanks

4 Answers
4

As mentioned in the comments, you are trying to get the ID in the taxonomy archive (template-taxonomy.php) which is not a post object and has no record in the database. It just tries to show some posts and you may get the first post ID when you use get_te_ID() function in that archive page.

Using some themes or plugins, you are able to create a page and use that as an archive page. In that case, the get_the_ID() function is able to return the actual page ID (Out of the loop) because it is a real post object and it has a place in the database.

Leave a Reply

Your email address will not be published. Required fields are marked *