How to get current page ID outside the loop?

  • 3
    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 – Pieter Goosen Sep 17 '14 at 14:06
  • <?php global $post; $thePostID=$post->ID;?> <?php elseif($thePostID==35) : ?> – Muhammad Shoaib Murtaza Sep 17 '14 at 14:12
  • 3
    Please file an edit with all the extra code/info. Don't use the comment section for stuff that should be in your question :-) – Pieter Goosen Sep 17 '14 at 14:14
  • Your post has been automatically flagged as low quality, please comply to my requests above :-) – Pieter Goosen Sep 17 '14 at 14:15
  • 1
    As I said, all of that info should go into your question, not in the comments section. Please edit your question – Pieter Goosen Sep 17 '14 at 14:19


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 – Muhammad Shoaib Murtaza Sep 17 '14 at 14:01
  • 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... – caramba Sep 17 '14 at 14:04
  • 2
    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(); – Muhammad Shoaib Murtaza Sep 17 '14 at 14:09
  • first one was correct... – Muhammad Shoaib Murtaza Sep 17 '14 at 14:39
  • 2
    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. – s_ha_dum Aug 19 '15 at 13:59

You can simply do,

$page_id = get_queried_object_id();
  • 7
    This should be marked as the answer... – Lezz Jan 28 '20 at 9:59
  • 4
    Agreed. This should be the answer. – CJWEB Mar 8 '20 at 4:44
  • Definately it should be the right answer. I'm trying to get the current id of a post or a page, and this is the only way it gives me the right Id without having to hardcode conditions. – Felipe Rugai May 22 '20 at 15:38
  • Brilliant, right answer for me – Nuno Sarmento Nov 19 '20 at 22:41

you can do it by adding below code.it will give you current page id.

 $postid = get_the_ID();
 echo $postid;
  • 10
    get_the_ID() is a Loop function-- aka, it is meant to be used inside the Loop. Therefore, it doesn't really address the question of "How to get current page id outside the loop?" – s_ha_dum Aug 19 '15 at 13:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.