How to get current page ID outside the loop?

  • How to get current page ID outside the loop?

    Strange, how are you using the code, what have you tried. What errors are you getting. As it stands, it is difficult to help you and all answers is a shot in the dark. Please file an [edit]

    Please file an [edit] with all the extra code/info. Don't use the comment section for stuff that should be in your question :-)

    Your post has been automatically flagged as low quality, please comply to my requests above :-)

    i m not getting any errors, actually i want to display google map on my page, so map is't displaying...

    in header.php i am using if else to showing according to page ids

    As I said, all of that info should go into your question, not in the comments section. Please [edit] your question

    Dear @Programmer, please read [ask]. You received automatic flags about the quality of your post. You got suggestions how to fix that. Please try to get over that so your question can stay open and you don't receive down votes. Thank you.

    You've accepted an answer already but the correct answer (arguably a duplicate question) is here:

  • caramba

    caramba Correct answer

    6 years ago


    global $post;
    echo $post->ID;

    or (I don't know the difference)

    global $wp_query;
    echo $wp_query->post->ID;

    i have tried all the stuff found on google but nothing happened

    it's hard to know what "all the stuff you found" is :) make sure the code is in a function, that you call that function and start debuging with echoing something else before which has to be visible...

    i did't getting id using function, and the "stuff" is `global $wp_query; $thePostID = $wp_query->post->ID; ` `global $post; $thePostID = $post->ID; ` `global $wp_query; $page = $wp_query->get_queried_object(); $page_id = $page->ID; ` `$page_id = get_queried_object_id(); `

    first one was correct...

    These solutions will give you page ID only if used before the Loop starts. Once the Loop starts, `$post` will be set to each post in the Loop in turn.

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM