WordPress Get the Page ID outside the loop WordPress Get the Page ID outside the loop php php

WordPress Get the Page ID outside the loop


If you're using pretty permalinks, get_query_var('page_id') won't work.

Instead, get the queried object ID from the global $wp_query:

// Since 3.1 - recommended!$page_object = get_queried_object();$page_id     = get_queried_object_id();// "Dirty" pre 3.1global $wp_query;$page_object = $wp_query->get_queried_object();$page_id     = $wp_query->get_queried_object_id();


You can also create a generic function to get the ID of the post, whether its outside or inside the loop (handles both the cases):

<?php/** * @uses WP_Query * @uses get_queried_object() * @see get_the_ID() * @return int */function get_the_post_id() {  if (in_the_loop()) {       $post_id = get_the_ID();  } else {       global $wp_query;       $post_id = $wp_query->get_queried_object_id();         }  return $post_id;} ?>

And simply do:

$page_id = get_the_post_id();


Use this global $post instead:

global $post;echo $post->ID;