How to get current page ID outside the loop?

How to get current page ID outside the loop?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Try

global $post;
echo $post->ID;

or (I don’t know the difference)

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

Method 2

You can simply do,

$page_id = get_queried_object_id();

Method 3

For those of you who this still isn’t working for, you will need to use some sort of add_action (you can choose which one you want to use). For my example, this will return the current page ID without any problems, regardless of whether in a plugin folder, functions php, or elsewhere.

add_action('template_redirect', 'showid');

function showid(){
    global $wp_query;
    $theid = intval($wp_query->queried_object->ID);
    echo $theid;
}

Good luck and happy coding!

Method 4

Outside the loop :

  //remember to call wp_reset_postdata(); after while loop
  // otherwise you will get wrong id.
   global $post;
   $post_id =  $post->ID;

Inside the loop:

while (have_posts()) {
    the_post();
    $post_id = the_ID();
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x