2

This one is pretty weird.

This code:

$post->ID 

Displays right ID every time excepting the blog page (the page set as blog on /wp-admin/options-reading.php).

On that page $post->ID returns the ID of first blog post for given page.

Now, the tricky part, I've tried to remove all the loops from all my pages, totally erased loop.php file, disabled all the widgets that might have been affecting $post and it still returns the wrong ID.

Any hints?

My index.php is pretty standard:

<?php get_header();?> <?php get_template_part( 'loop', 'index' ); ?> <?php get_footer(); ?> 

And the loop.php is:

<?php while ( have_posts() ) : the_post(); ?> contents <?php endwhile; ?> 

Maybe the problem is I'm trying to get the ID in header.php?

And yes, wp_reset_postdata() doesn't seem to help as well :/

3
  • 1
    Are you just trying to get that specific ID, or do you want to have some general functionality dealing with the IDs? If the first is the case, you could use get_option('page_for_posts');. Commented Aug 8, 2013 at 20:08
  • I was trying to get metabox value, so general functionality dealing with the IDs, anyways it's resolved now, thanks for your time! Commented Aug 8, 2013 at 20:20
  • Here's a similar thread: wordpress.stackexchange.com/questions/150192/… Commented Mar 5, 2019 at 8:27

1 Answer 1

12

On that page $post->ID returns the ID of first blog post for given page.

That is how it works. $post is set to the first post in the Loop. On single posts and pages that is the same as the post or page. On archive pages it is the first post in the result set. And if you think about that, both are really the same thing. Single posts and pages only have one result in the set which happens to match the post or page that you expect.

Now, the tricky part, I've tried to remove all the loops from all my pages, totally erased loop.php file, disabled all the widgets that might have been affecting $post and it still returns the wrong ID.

The main query runs before your template loads and $post is set in that process. Removing things from the template won't change that.

Any hints?

Yes. Don't rely on $post except inside a proper Loop. If you need information about the page itself use:

$pobj = get_queried_object(); var_dump($pobj); // debugging 

Reference:

http://codex.wordpress.org/Function_Reference/get_queried_object

2
  • Clever, I have never heard about this solution before. Commented Aug 8, 2013 at 20:19
  • Awesome. Freaking awesome. Saved my life with an issue in which I used several get_template_part() inside front-page.php as a static homepage, and a post id kept being used instead of the static homepage page. Commented May 2, 2023 at 2:24

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.