$post>ID displays wrong post ID

I’ve asked a question about listing all sub-pages before:

Listing all sub-pages?

Read More

But all the questions were wrong.

Anyways, I have now simpler question.

global $post;
echo $post>ID

Works totally fine, but while on pages sidebars only. When it’s next to the blog loop (in a blog section) it goes crazy, for example Blog has ID of 216 (and $post>ID in loop.php shows 216), but the $post>ID in the sidebar shows 87. Why is this happening? How to fix that?

Thank you!

[edit]

I have a suspicion that loop and sidebar are both included in index page separately and loop is getting different post ID than sidebar. The big question is how to change that.

[edit for Rarst]

 wp_reset_postdata();

                global $post;

                $children = wp_list_pages('title_li=&child_of='.$post->ID.'&echo=0');
                echo $children;

Gives the same result. It works with pages, not blog. I have a normal loop, as like in Twenty Ten for example.

Related posts

Leave a Reply

2 comments

  1. If i understand correctly you are trying to display a list of child pages of a page in a widget, if so then first check if you are on a page using the conditional tag is_page()
    then you can use $wp_query->get_queried_object_id() like t31os has pointed out so your widget display function should look like this:

    if (is_page()){
        Global $wp_query;
        $current_page_id = $wp_query->get_queried_object_id();
        $children = wp_list_pages('title_li=&child_of='.$current_page_id.'&echo=0');
        echo $children;
    }
    

    So only if you are on a page this code will run

  2. $post changes every time the_post() or setup_postdata() are used – which is in most of the loops.

    Use wp_reset_postdata() to kick it back to original data.

    Edit

    $post holds data of individual post, set up during the Loop. It makes no sense to use it out of that context.

    To process multiple pages you need to query for them (with get_pages() for example) and work with that.