How to get current page ID outside the loop?

How to get current page ID outside the loop?

Topic id pages Wordpress

Category Web


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();
}

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!


Try

global $post;
echo $post->ID;

or (I don't know the difference)

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

You can simply do,

$page_id = get_queried_object_id();

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.