36

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
56

Try

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
  • 1
    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
17

You can simply do,

$page_id = get_queried_object_id();
-7

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

 $postid = get_the_ID();
 echo $postid;
  • 9
    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.