WordPress Get the Page ID outside the loop

Atif Mohammed Ameenuddin picture Atif Mohammed Ameenuddin · Jun 27, 2010 · Viewed 103.4k times · Source

I want to get the page ID before starting the loop in WordPress. I am using

$page = get_query_var('page_id');

Apparently, it returns nothing.

I just want to check a page for its ID and add a class to <body> tag based on it.

Answer

TheDeadMedic picture TheDeadMedic · Jun 27, 2010

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.1
global $wp_query;

$page_object = $wp_query->get_queried_object();
$page_id     = $wp_query->get_queried_object_id();